using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using MBLocale;

/// <summary>
/// Summary description for DynamicDisplayI
/// </summary>
public class DynamicDisplayI
{

    PageCommonFunctions PCF = new PageCommonFunctions();
    BindControl BC = new BindControl();
    HDDatabase HDD = new HDDatabase();
    HtmlForm frmMainObj = null;
    DataSet dsePageInfoMain = null;
    int rowcount = 0; // Added by srivatsan for transaction document changes
    //DataRow drObjectRights = null;
    /// <summary>
    /// Generates the dynamic page based on the page set id.
    /// Page is displayed with basic design. 
    /// Basic design is Two controls in one row and caption in top of that control.
    /// </summary>
    public DynamicDisplayI()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    public void disableControls(Control cntrl)//implemnted by sanal on 30th July 2008
    {
        //string temp = "";
        foreach (Control cc in cntrl.Controls)
        {
            //if (cc.ID!=null)
            //    if (cc.ID.ToLower().IndexOf("btnsave") > -1)
            //        temp = cc.ID;
            if (cc is TextBox)
            {
                TextBox tb = (TextBox)cc;
                if (tb.ID.ToLower() != "feedbacktext")
                {
                    tb.Enabled = false;
                    disableControls(cc);
                }
            }
            if (cc is DropDownList)
            {
                DropDownList tb = (DropDownList)cc;
                tb.Enabled = false;
                disableControls(cc);
            }
            if (cc is Button)
            {
                Button tb = (Button)cc;
                tb.Visible = false;
                disableControls(cc);
            }
            if (cc is HtmlInputButton)
            {
                HtmlInputButton tb = (HtmlInputButton)cc;
                tb.Visible = false;
                //disableControls(cc);
            }
            if (cc is CheckBox)
            {
                CheckBox tb = (CheckBox)cc;
                if (tb.ID.ToLower() != "rbtnadmin" && tb.ID.ToLower() != "rbtnuser")
                {
                    tb.Enabled = false;
                }
                //disableControls(cc);
            }
            if (cc is HtmlImage)
            {
                HtmlImage tb = (HtmlImage)cc;
                tb.Style.Add("display", "none");
                //disableControls(cc);
            }
            if (cc is HtmlInputImage)
            {
                HtmlInputImage tb = (HtmlInputImage)cc;
                tb.Style.Add("display", "none");
                //disableControls(cc);
            }
            if (cc is Image)
            {
                Image tb = (Image)cc;
                tb.Style.Add("disabled", "true");
                //disableControls(cc);
            }
            if (cc is FileUpload)
            {
                FileUpload tb = (FileUpload)cc;
                tb.Enabled = false;
                //disableControls(cc);
            }
            if (cc is ListBox)
            {
                ListBox lb = (ListBox)cc;
                lb.Enabled = false;
            }
            disableControls(cc);
        }
    }
    public Control FindControl(ControlCollection frmControl, string strControlId)
    {
        Control cRet = null;
        foreach (Control con in frmControl)
        {
            if (con.ID != null)
                if (con.ID.ToLower() == strControlId.ToLower())
                    return con;
        }

        foreach (Control cn in frmControl)
            if (cn.Controls.Count > 0)
            {
                cRet = FindControl(cn.Controls, strControlId);
                if (cRet != null) break;
            }
        return cRet;
    }

    private void refreshSectionnames(ref DataTable dt)//Added By Dhanapal On Dec 09 2010
    {
        foreach (DataRow dr in dt.Rows)
        {
            if (dr["section_name"] == null || dr["section_name"].ToString().Trim() == "")
            {
                dr["section_name"] = "__MB_EMPTY_SECTION";
            }

        }
       
    }

    private void refreshSysVarSectionNames(ref DataTable dt)//Added By Dhanapal On Dec 09 2010
    {
        foreach (DataRow dr in dt.Rows)
        {
            switch (dr["control_id"].ToString())
            {
                case "af_row_id":
                    dr["section_name"] = "__SYS_VAR__";
                    break;
                case "created_by":
                    dr["section_name"] = "__SYS_VAR__";
                    break;
                case "modified_at":
                    dr["section_name"] = "__SYS_VAR__";
                    break;
                case "created_at":
                    dr["section_name"] = "__SYS_VAR__";
                    break;
                case "modified_by":
                    dr["section_name"] = "__SYS_VAR__";
                    break;
                case "owner_id": 
                    dr["section_name"] = "__SYS_VAR__";
                    break;
            }

        }

    }
    public bool Load(string strPgsId, HtmlForm frmObj, ref DataSet dsePageInfo, DataSet dsInput, DataSet dsTax)
    {

        bool blnStatus = true;
        HtmlTable htaMain = new HtmlTable();
        if (dsInput != null)
        {
            htaMain.ID = "tblDynamicMain1";
        }
        else
        {
            htaMain.ID = "tblDynamicMain";
        }
        htaMain.Width = "100%";
        string strPageId = "";
        dsePageInfoMain = dsePageInfo;
        if (dsInput != null) // Check for transaction document page
        {
            // If transaction document page, add static settings the dataset.
            AddTransactionDocumentSetting(ref dsePageInfo);
        }
        DataTable dtaPageSet = dsePageInfo.Tables["PageSet"];
        DataTable dtaPage = dsePageInfo.Tables["Page"];
        DataTable dtaPageKeys = dsePageInfo.Tables["PageKeys"];
        DataTable dtaPageCtrl = dsePageInfo.Tables["PageCtrl"];
        refreshSysVarSectionNames(ref dtaPageCtrl);//Added By DHanapal
        refreshSectionnames(ref dtaPageCtrl);//Added By DHanapal
        dtaPageCtrl.Columns.Add(new DataColumn("attrib_size"));//The attrib Size was Added

        for (int i = 0; i < dtaPage.Rows.Count; i++)
        {
            strPageId = dtaPage.Rows[i]["page_id"].ToString();
            string sAF_ROW_ID = dtaPage.Rows[i]["af_row_id"].ToString();
            DataTable dtAttrib_Size = HDD.GetDataTable("select attrib_id, attrib_size, attrib_data_type from sy_obj_att obj_att inner join sy_obj obj on obj.af_row_id=obj_att.object_id where obj.object_id='" + dtaPage.Rows[i]["object_id"].ToString() + "'");

            foreach (DataRow dr in dtaPageCtrl.Select("page_id='" + sAF_ROW_ID + "'"))
            {
                DataRow[] drr = dtAttrib_Size.Select("attrib_id = '" + dr["control_attrib_id"].ToString() + "'");
                if (drr.Length > 0)
                {
                    if (drr[0]["attrib_data_type"].ToString() == "TX")
                        dr["attrib_size"] = drr[0]["attrib_size"].ToString();
                }
            }

           
            /********Changed Done By Dhanapal On Dec 09 2010**************/

            DataRow[] drPageCtrlOrdered = getOrderedpageCtrl(dtaPageCtrl , sAF_ROW_ID);

           /*************************************************************/

           LoadPageMember(dtaPage, frmObj, htaMain, drPageCtrlOrdered, dtaPageKeys, i, dsInput, dsTax); //The Page was Formed Here and the order by section name and sequence was done here.
           //LoadPageMember(dtaPage, frmObj, htaMain, dtaPageCtrl.Select("page_id='" + sAF_ROW_ID + "'", "control_seq,section_name asc"), dtaPageKeys, i, dsInput, dsTax); //The Page was Formed Here and the order by section name and sequence was done here.
        }
        string tablecellname = GetHtmlTableCellName(dsInput); // Added by srivatsan to get table cell name on which the output will be rendered
        //HtmlTableCell htcObj = (HtmlTableCell)FindControl(frmObj.Controls, "tdcPage");//HtmlTableCell htcObj = (HtmlTableCell)frmObj.FindControl("tdcPage");        
        HtmlTableCell htcObj = (HtmlTableCell)FindControl(frmObj.Controls, tablecellname);
        //htaMain.Border =1;
        htaMain.CellPadding = 0;
        htaMain.CellSpacing = 0;
        htaMain.EnableViewState = false;
        htcObj.Controls.Add(htaMain);
        return blnStatus;

    }

   private DataRow[] getOrderedpageCtrl(DataTable dtPageCtrl, string pageId)//Added By Dhanapal on Dec 09 2010 For Sectioning Row in Sequence by Ctrl and Section Name
    {
        DataTable dtTempPageCtrl = new DataTable();
        dtTempPageCtrl = dtPageCtrl.Clone();
        DataRow[] drPageControls = dtPageCtrl.Select("page_id='" + pageId + "'", "control_seq,section_name asc");
        ArrayList arlEmptySection = new ArrayList();
        ArrayList arlDistinctSectionName = new ArrayList();

        foreach (DataRow dr in drPageControls) // To get The Distinct Section Names
        {
            if (!arlDistinctSectionName.Contains(dr["section_name"].ToString()))
            {
                arlDistinctSectionName.Add(dr["section_name"].ToString());
            }

        }

        foreach (string strSectionName in arlDistinctSectionName) // The Distinct Section Names Were Iterated
        {
            foreach (DataRow drPageRw in drPageControls)
            {
                if (drPageRw["section_name"].ToString() == strSectionName)
                {
                    dtTempPageCtrl.ImportRow(drPageRw);

                }

            }
        }
        return dtTempPageCtrl.Select("");
    }
    

    public bool LoadPageMember(DataTable dtaPage, HtmlForm frmObj, HtmlTable htaMain, DataRow[] droPageCtrl,
        DataTable dtaPageKeys, int intPageSeq, DataSet dsInput, DataSet dsTax)
    {
        bool blnStatus = true;
        int intRowCnt = 1;
        bool blnMultiplePage = Convert.ToBoolean(dtaPage.Rows[intPageSeq]["multiple_recs_page"].ToString());
        string strPageId = dtaPage.Rows[intPageSeq]["page_id"].ToString();
        frmMainObj = frmObj;
        if (blnMultiplePage)
        {
            if (frmObj.Page.IsPostBack) //If it is postback to get the no fo rows present
            {
                if (frmObj.Page.Request.Form["_sys" + strPageId + "_RowCount"] != null)
                    intRowCnt = Convert.ToInt32(frmObj.Page.Request.Form["_sys" + strPageId + "_RowCount"].ToString());
                else if (frmObj.Page.Request.Form["ctl00$_sys" + strPageId + "_RowCount"] != null)
                    intRowCnt = Convert.ToInt32(frmObj.Page.Request.Form["ctl00$_sys" + strPageId + "_RowCount"].ToString());
            }

            intRowCnt = GetRowCountForTransactionDocumentPage(dsInput, frmObj, intRowCnt); // Added for Transaction doeumnt page Row count
        }
        LoadPageMember(dtaPage, frmObj, htaMain, droPageCtrl, dtaPageKeys, intPageSeq, 0, intRowCnt, dsInput, dsTax);
        return blnStatus;
    }

    //Added to get row count for transaction document page
    private int GetRowCountForTransactionDocumentPage(DataSet dsInput, HtmlForm frmObj, int intRowCnt)
    {
        try
        {
            if (dsInput != null)
            {
                if (frmObj.Page.IsPostBack)
                {
                    intRowCnt = Convert.ToInt32(HttpContext.Current.Session["hfrowcount"].ToString());
                    HiddenField hfrowcount = (HiddenField)frmObj.FindControl("ctl00$ContentPlaceHolder3$hfrowcount");
                    if (hfrowcount != null)
                    {
                        string value = hfrowcount.Value;
                        if (value.ToLower() == "add")
                        {
                            intRowCnt = intRowCnt + 1;
                        }
                        else if (value.ToLower() == "del")
                        {
                            //intRowCnt = intRowCnt - 1;
                        }
                        HttpContext.Current.Session["hfrowcount"] = intRowCnt.ToString();
                        hfrowcount.Value = "";
                    }

                }
                else
                {
                    if (dsInput != null)
                    {
                        if (dsInput.Tables.Count > 0)
                        {
                            if (dsInput.Tables[0].Rows.Count > 0)
                            {
                                intRowCnt = dsInput.Tables[0].Rows.Count;

                                if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("transdoc.aspx"))  // Added by srivatsan
                                {
                                    HttpContext.Current.Session["hfrowcount"] = intRowCnt.ToString();
                                }
                            }
                            else
                            {
                                HttpContext.Current.Session["hfrowcount"] = intRowCnt.ToString();
                            }
                        }
                        else
                        {
                            HttpContext.Current.Session["hfrowcount"] = intRowCnt.ToString();
                        }
                    }
                }
                rowcount = intRowCnt; // added by srivatsan
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetRowCountForTransactionDocumentPage :" + ex.Message);
        }

        return intRowCnt;
    }


    public DataSet AddTransactionDocumentSetting(ref DataSet dsePageInfo)
    {
        if (dsePageInfo != null)
        {
            if (dsePageInfo.Tables.Count > 0)
            {
                // Added by srivatsan on May 08 2009 for transaction document
                dsePageInfo.Tables["Page"].Rows[0]["multiple_recs_page"] = "true";
                dsePageInfo.Tables["Page"].Rows[0]["page_view"] = 1;
                int controlcount = dsePageInfo.Tables["PageCtrl"].Select("control_visible = 'true'").Length;
                dsePageInfo.Tables["Page"].Rows[0]["control_per_row"] = controlcount;
                dsePageInfo.Tables["Page"].Rows[0]["first_row_caption_only"] = "true";

                //
            }
        }
        return dsePageInfo;
    }


    // This function will retrieve the HtmlTableCell Name on which the output need to be rendered.
    // By default it will be tdcPageDetail.
    private string GetHtmlTableCellName(DataSet dsInput)
    {
        string result = "tdcPage";
        try
        {
            if (dsInput != null)
            {
                result = "tdcPagedetail";
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetHtmlTableCellName: " + ex.Message);
        }
        return result;
    }

    // Commented by srivatsan On Oct 26 2009.
    // Commented for reference.
    ////public bool Load(string strPgsId, HtmlForm frmObj, DataSet dsePageInfo)
    ////{
    ////    bool blnStatus = true;
    ////    HtmlTable htaMain = new HtmlTable();
    ////    htaMain.ID = "tblDynamicMain";
    ////    htaMain.Width = "100%";
    ////    string strPageId = "";

    ////    dsePageInfoMain = dsePageInfo;

    ////    DataTable dtaPageSet = dsePageInfo.Tables["PageSet"];
    ////    DataTable dtaPage = dsePageInfo.Tables["Page"];
    ////    DataTable dtaPageKeys = dsePageInfo.Tables["PageKeys"];
    ////    DataTable dtaPageCtrl = dsePageInfo.Tables["PageCtrl"];
    ////    dtaPageCtrl.Columns.Add(new DataColumn("attrib_size"));

    ////    for (int i = 0; i < dtaPage.Rows.Count; i++)
    ////    {
    ////        strPageId = dtaPage.Rows[i]["page_id"].ToString();
    ////        string sAF_ROW_ID = dtaPage.Rows[i]["af_row_id"].ToString();
    ////        DataTable dtAttrib_Size = HDD.GetDataTable("select attrib_id, attrib_size, attrib_data_type from sy_obj_att obj_att inner join sy_obj obj on obj.af_row_id=obj_att.object_id where obj.object_id='" + dtaPage.Rows[i]["object_id"].ToString() + "'");

    ////        foreach (DataRow dr in dtaPageCtrl.Select("page_id='" + sAF_ROW_ID + "'"))
    ////        {
    ////            DataRow[] drr = dtAttrib_Size.Select("attrib_id = '" + dr["control_attrib_id"].ToString() + "'");
    ////            if (drr.Length > 0)
    ////            {
    ////                if (drr[0]["attrib_data_type"].ToString() == "TX")
    ////                    dr["attrib_size"] = drr[0]["attrib_size"].ToString();
    ////            }
    ////        }

    ////        LoadPageMember(dtaPage, frmObj, htaMain, dtaPageCtrl.Select("page_id='" + sAF_ROW_ID + "'", "control_seq asc"), dtaPageKeys, i);
    ////    }

    ////    HtmlTableCell htcObj = (HtmlTableCell)FindControl(frmObj.Controls, "tdcPage");//HtmlTableCell htcObj = (HtmlTableCell)frmObj.FindControl("tdcPage");        
    ////    htaMain.Border = 0;
    ////    htaMain.CellPadding = 0;
    ////    htaMain.CellSpacing = 0;
    ////    htaMain.EnableViewState = false;
    ////    htcObj.Controls.Add(htaMain);

    ////    return blnStatus;
    ////}

    //public bool LoadPageMember(DataTable dtaPage, HtmlForm frmObj, HtmlTable htaMain, DataRow[] droPageCtrl,
    // commented for reference
    //    DataTable dtaPageKeys, int intPageSeq)
    //{
    //    bool blnStatus = true;
    //    int intRowCnt = 1;
    //    bool blnMultiplePage = Convert.ToBoolean(dtaPage.Rows[intPageSeq]["multiple_recs_page"].ToString());
    //    string strPageId = dtaPage.Rows[intPageSeq]["page_id"].ToString();
    //    frmMainObj = frmObj;
    //    if (blnMultiplePage)
    //    {
    //        if (frmObj.Page.IsPostBack)
    //        {
    //            if (frmObj.Page.Request.Form["_sys" + strPageId + "_RowCount"] != null)
    //                intRowCnt = Convert.ToInt32(frmObj.Page.Request.Form["_sys" + strPageId + "_RowCount"].ToString());
    //            else if (frmObj.Page.Request.Form["ctl00$_sys" + strPageId + "_RowCount"] != null)
    //                    intRowCnt = Convert.ToInt32(frmObj.Page.Request.Form["ctl00$_sys" + strPageId + "_RowCount"].ToString());

    //        }
    //    }
    //    LoadPageMember(dtaPage, frmObj, htaMain, droPageCtrl, dtaPageKeys, intPageSeq, 0, intRowCnt);
    //    return blnStatus;
    //}

    private void addNoRightsMessage(HtmlTable htaMain, string sPageId)
    {
        Label lblMessage1 = new Label();
        lblMessage1.Text = "You do not have sufficient access permission.";
        lblMessage1.ForeColor = System.Drawing.Color.Red;
        HtmlTableCell htCell = new HtmlTableCell();
        HtmlTableRow htRow = new HtmlTableRow();
        htCell.Controls.Add(lblMessage1);
        htRow.Cells.Add(htCell);
        htaMain.Rows.Add(htRow);
    }

    private bool checkRightsForObject(HtmlTable htaMain, security objSec, string sPageId, string sObjectId, string Right)
    {
        bool bRights = true;
        if (!objSec.getObjectRightsForUser(sObjectId, Right))
        {
            if (htaMain.Rows.Count == 0) addNoRightsMessage(htaMain, sPageId);
            bRights = false;
        }
        return bRights;
    }

    //private bool hasAccess(string Rights)
    //{
    //    bool bReturn = false;

    //    if (drObjectRights != null)
    //    {
    //        bReturn = Convert.ToBoolean(drObjectRights[Rights]);
    //    }
    //    else
    //        bReturn = false;

    //    return bReturn;
    //}
    private string isRelationalField(string objId)
    {
        //abandoned as another functionality exists.
        return "";
        DataTable dtObjatt = new DataTable();
        dtObjatt = this.HDD.GetDataTable("select af_row_id from sy_obj where object_id='" + objId + "'");
        dtObjatt = this.HDD.GetDataTable("select attrib_id from sy_obj_mas_detail where object_id='" + dtObjatt.Rows[0]["af_row_id"].ToString() + "'");
        string ret = "";
        foreach (DataRow dr in dtObjatt.Rows)
            ret = ret + "," + dr["attrib_id"].ToString() + ",";
        return ret;
    }

    public bool LoadPageMember(DataTable dtaPage, HtmlForm frmObj, HtmlTable htaMain, DataRow[] droPageCtrl,
        DataTable dtaPageKeys, int intPageSeq, int intStartFrom, int intRowCnt, DataSet dsInput, DataSet dsTax)
    {
        bool blnStatus = true;
        DataRow droTemp;
        HtmlTableCell htc;
        string strCtrlDesc = "";
        int intCurrentRow = 0;
        string strCtrlId = "";
        string strCtrlColumn = "";
        string strBindRowID = "";
        string strActualCtrlId = "";
        string strCtrlWidth = "";
        string sAttrib_Size = "";
        string sInputFormatMask = "";
        htc = new HtmlTableCell();
        DataRow droPage = dtaPage.Rows[intPageSeq];
        ArrayList arlHtmlCells = new ArrayList();
        ArrayList arlSectionDistinctName = new ArrayList();
        
        
        string strMenuRowId = "";
        HDDatabase hdd = new HDDatabase();
        security objSec = new security();
        PageInfoLoad PIL = new PageInfoLoad();
        int intPosTotal = 0;

        // Srivatsan May 15 2009 Control events 
        DataSet dscontrolevents = new DataSet();
        dscontrolevents = dsePageInfoMain;


        if (frmObj.Page.Request.QueryString["mn"].ToString() != null)
        {
            strMenuRowId = frmObj.Page.Request.QueryString["mn"].ToString();
        }
        if (intStartFrom == 0)
        {
            PageHeaderAdd(htaMain, droPage, strMenuRowId, objSec, dsInput);
        }
        PageTooltipAdd(htaMain, droPage);//implemented by sanal on July 28, 2008
        string strPageId = dtaPage.Rows[intPageSeq]["page_id"].ToString();

        bool blnMultiplePage = Convert.ToBoolean(dtaPage.Rows[intPageSeq]["multiple_recs_page"].ToString());
        bool blnFirstRowCaptionOnly = false;
        if (dtaPage.Rows[intPageSeq]["first_row_caption_only"] == DBNull.Value)
        {
            blnFirstRowCaptionOnly = GlobalValues.FirstRowCaptionOnly;
        }
        else
        {
            blnFirstRowCaptionOnly = Convert.ToBoolean(dtaPage.Rows[intPageSeq]["first_row_caption_only"].ToString());
        }
        //string strPageId = dtaPage.Rows[intPageSeq]["page_id"].ToString();
        HtmlTable htaPageTable = new HtmlTable();
        if (intStartFrom > 0)
        {
            htaPageTable = (HtmlTable)FindControl(frmObj.Controls, "tbl_" + strPageId);//htaPageTable = (HtmlTable)frmObj.FindControl("tbl_" + strPageId);
        }
        if (dsInput == null)
        {
            htaPageTable.Attributes.Add("width", "100%");
        }

        htaPageTable.ID = "tbl_" + strPageId;
        htaPageTable.CellPadding = 0;
        htaPageTable.CellSpacing = 2; // This size used to change the space between Each Row in Page Ctrl modified by Dhanapal.c 29 nov 2010
        // htaPageTable.CellSpacing = 0;  // This Table Holds the page Ctrl attributes Dhanapal.c 29 nov 2010
        htaPageTable.Border = 0;

        if (blnMultiplePage)
        {
            if (FindControl(frmObj.Controls, "_sys" + strPageId + "_RowCount") == null)
            {
                HtmlInputHidden hihObj = new HtmlInputHidden();
                hihObj.ID = "_sys" + strPageId + "_RowCount";
                frmObj.Controls.Add(hihObj);


            }
        }
        bool blnSeqControl = false;
        bool blnCaption = true;
        string strPageView = "";
        if (droPage["page_view"] == DBNull.Value)
        {
            strPageView = GlobalValues.DefaultPageView;
        }
        else
        {
            strPageView = droPage["page_view"].ToString();
        }

        if (checkRightsForObject(htaPageTable, objSec, strPageId, droPage["object_id"].ToString(), "read") == true)
        {
            Hashtable hsControlValues = new Hashtable();
            //if (!frmObj.Page.IsPostBack)
            //{
            DataSet dsPageEvents = PIL.pageEventHandler(strPageId);

            if (dsPageEvents != null)
            {
                DataSet dsPageInfo = dtaPage.DataSet.Copy(); ;
                if (dsPageEvents.Tables.Count > 0)
                    PIL.triggerEvent(dsPageEvents, "PL", ref hsControlValues, ref dsPageInfo, frmObj);
                dsPageInfo.Dispose();
                dsPageInfo = null;
            }
            //}

            //////string sSql = "select attrib_id from sy_obj_att obj_att inner join sy_obj obj on obj.af_row_id=obj_att.object_id where obj.object_id='" + droPage["object_id"].ToString().Replace("'", "''") + "' and obj_att.is_key='true'";
            //////string sKeyAtt = hdd.GetColumnValue(sSql);
            DataTable dtObjatt = new DataTable();
            //string sSql = "select attrib_id from sy_obj_att obj_att inner join sy_obj obj on obj.af_row_id=obj_att.object_id where obj.object_id='" + droPage["object_id"].ToString().Replace("'", "''") + "' and obj_att.is_key='true'";
            string sSql = "select attrib_id,attrib_name,is_key,is_primary,object_tooltip from sy_obj_att obj_att inner join sy_obj obj on obj.af_row_id=obj_att.object_id where obj.object_id='" + droPage["object_id"].ToString().Replace("'", "''") + "'";
            //string sSql = "select attrib_id,is_key,is_primary from sy_obj_att obj_att object_id='" + droPage["object_id"].ToString().Replace("'", "''") + "'";
            dtObjatt = hdd.GetDataTable(sSql);
            string sKeyAtt = ""; string sPrimaryAtt = ""; string sRelationalField = ""; Hashtable Tooltips = new Hashtable();
            foreach (DataRow dr in dtObjatt.Rows)
                Tooltips.Add(dr["attrib_id"].ToString(), dr["object_tooltip"].ToString());
            try
            {
                DataRow[] drKeys = dtObjatt.Select("is_key='true'");
                if (drKeys.Length > 0)
                    sKeyAtt = drKeys[0]["attrib_id"].ToString();
                DataRow[] drPrKeys = dtObjatt.Select("is_primary='true'");
                for (int k = 0; k < drPrKeys.Length; k++)
                    sPrimaryAtt += "," + drPrKeys[k]["attrib_id"].ToString() + ",";
                //sPrimaryAtt = dtObjatt.Select("is_primary='true'")[0]["attrib_id"].ToString();

                // Added for Transaction Document Page
                AddRequiredFieldValuesToHiddenVariable(dsInput, frmObj, drPrKeys);
            }
            catch (Exception e) { }
            dtObjatt = null;

            sRelationalField = isRelationalField(droPage["object_id"].ToString().Replace("'", "''"));

            bool bEdit = objSec.getObjectRightsForUser(droPage["object_id"].ToString(), "Edit") || objSec.getObjectRightsForUser(droPage["object_id"].ToString(), "Create");
            //string datetimscript = "";

            DataRow[] drTotals = null;
            if (dsInput != null) // Check for Transaction document page
            {
                AddTransDocCaptions(htaPageTable, droPageCtrl, dtaPageKeys);//

                //DataRow[] drTotals = getTotalFields(droPageCtrl[0]["page_id"].ToString());
                drTotals = getTotalFields(droPageCtrl[0]["page_id"].ToString());
            }

            for (int j = intStartFrom; j < intRowCnt; j++)
            {

                
                arlHtmlCells = new ArrayList();
                arlSectionDistinctName = new ArrayList(); //added By Dhanapal Contains The Distinct Section Name
                intCurrentRow = j + 1;
                //if control caption repeat is false and control row is greater than 1 then no need to add the caption
                if (blnFirstRowCaptionOnly)
                {
                    if (j > 0)
                    {
                        blnCaption = false;
                    }
                }

              
                
                for (int i = 0; i < droPageCtrl.Length; i++)
                {
                    droTemp = droPageCtrl[i];
                    /////strActualCtrlId = droTemp["control_id"].ToString(); //used for passing into control_init method
                    /////strCtrlId = droTemp["control_id"].ToString();
                    /////j
                    String strsectionname = droTemp["section_name"].ToString();
                    strActualCtrlId = droTemp["control_attrib_id"].ToString();
                    strCtrlId = droTemp["control_attrib_id"].ToString();

                    strBindRowID = droTemp["control_bind_id"].ToString();
                    strCtrlWidth = droTemp["control_width"].ToString();
                    sAttrib_Size = droTemp["attrib_size"].ToString();
                    if (droTemp.Table.Columns.Contains("input_mask_format"))
                        sInputFormatMask = droTemp["input_mask_format"].ToString();
                    strCtrlId = strPageId + "_" + strCtrlId;
                    string sIsKey = "false"; string sIsPrimary = "false"; string sIsRelationalField = "false";
                    if (strActualCtrlId.ToLower() == sKeyAtt.ToLower())
                        sIsKey = "true";
                    //if (strActualCtrlId.ToLower() == sPrimaryAtt.ToLower())
                    if (sPrimaryAtt.ToLower().IndexOf("," + strActualCtrlId.ToLower() + ",") > -1)
                        sIsPrimary = "true";
                    if (sRelationalField.ToLower().IndexOf("," + strActualCtrlId.ToLower() + ",") > -1)
                        sIsRelationalField = "true";



                    //DataSet ds = droTemp.Table.DataSet;

                    if (droTemp.Table.Columns.Contains("read_only"))
                        if (droTemp["read_only"] != System.DBNull.Value)
                            bEdit = !Convert.ToBoolean(droTemp["read_only"].ToString());

                    if (blnMultiplePage)
                        strCtrlId += "_" + intCurrentRow.ToString();

                    if (droTemp["is_seq_control"] != System.DBNull.Value)
                        blnSeqControl = (Convert.ToBoolean(droTemp["is_seq_control"].ToString()));

                    if (droTemp["control_html"].ToString() != "HI" && Convert.ToBoolean(droTemp["control_visible"].ToString() == "" ? "false" : droTemp["control_visible"].ToString()) != false)
                    {
                        strCtrlDesc = droTemp["control_name"].ToString();
                        strCtrlColumn = droTemp["control_attrib_id"].ToString();
                        /*if (PCF.IsParentPageKeyControl(strCtrlColumn, dtaPage, dtaPageKeys, intPageSeq) == false)
                        {*/
                        string sObject_id = dtaPage.Rows[0]["object_id"].ToString();
                        string strCtrlHtml = droTemp["control_html"].ToString();
                        string strDefaultVal = droTemp["default_value"].ToString();

                        if (hsControlValues.Contains("[" + sObject_id + "].[" + strActualCtrlId + "]"))
                            strDefaultVal = Convert.ToString(hsControlValues["[" + sObject_id + "].[" + strActualCtrlId + "]"]);

                        //string sSql = "select is_key from sy_obj_att where object_id='" + droPage["object_id"].ToString().Replace("'", "''") + "' and attrib_id='" + droTemp["control_attrib_id"].ToString().Replace("'", "''") + "'";
                        //string sIsKey = hdd.GetColumnValue(sSql);

                        if (HttpContext.Current.Request.QueryString["VMODE"] != null)
                            if (HttpContext.Current.Request.QueryString["VMODE"] == "1")
                                bEdit = false;//strCtrlHtml = "";

                        string sToolTip = getValueFromKey(Tooltips, strCtrlColumn);
                       
                        addSection(ref arlHtmlCells, strPageView, droTemp, droPage, ref arlSectionDistinctName);//implemented by sanal on 22Aug2008 to add sections in the controls rendered //reused by Dhanapal For Section
                        PCF.ControlInit(htc, intCurrentRow, strPageView, strCtrlId, strCtrlDesc, strBindRowID, strCtrlHtml, arlHtmlCells,
                             blnSeqControl, BC, strDefaultVal, blnCaption, strActualCtrlId, strCtrlWidth, sObject_id, sIsKey.ToLower(), sIsPrimary.ToLower(), blnMultiplePage, bEdit, sAttrib_Size, droTemp, dtaPageKeys, sIsRelationalField, sToolTip, sInputFormatMask, dsInput, drTotals, frmObj, dsTax, strPageId);
                        
                        /*
                         * removed all the control case and moved to page common function
                         * for better followup
                        */
                        //}
                    }
                    if (droTemp["control_html"].ToString() == "HI" && Convert.ToBoolean(droTemp["control_visible"].ToString()) == true)
                    {
                        HtmlInputHidden hihObj = new HtmlInputHidden();
                        hihObj.ID = strCtrlId;
                        frmObj.Controls.Add(hihObj);
                    }
                    //if (droTemp["control_attrib_id"].ToString() == "af_row_id")
                    if (!Convert.ToBoolean(droTemp["control_visible"].ToString() == "" ? "false" : droTemp["control_visible"].ToString()))
                    {
                        HiddenField hf = new HiddenField();
                        hf.ID = strCtrlId;

                        //TextBox txt = new TextBox(); // Srivatsan
                        //txt.ID = strCtrlId;
                        //txt.Style.Add("display", "none");

                        if (HttpContext.Current.Request.QueryString["PK"] == null)
                        {
                            if (HttpContext.Current.Request.QueryString["pgs_id"] != null)
                            {
                                if (HttpContext.Current.Request.QueryString["pgs_id"].ToString().ToLower() == "c6e7de1b8b5f0835") // pgs_id = 'ps_notes'
                                {
                                    hf.Value = GetNotesHiddenFieldData(strCtrlId, dsePageInfoMain);
                                }
                                else
                                {
                                    if (droTemp.Table.Columns.Contains("default_value"))
                                        hf.Value = droTemp["default_value"].ToString();
                                }
                            }
                        }
                        else
                        {
                            //if (droTemp.Table.Columns.Contains("default_value"))
                            //hf.Value = droTemp["default_value"].ToString();   // commented by srivatsan
                            if (dsInput != null) //added for hidden field update
                            {
                                if (!frmObj.Page.IsPostBack)
                                {
                                    string bindtext = "";
                                    Control conobj = (Control)hf;
                                    hf.Visible = true;
                                    //Control conobj = (Control)txt;
                                    //txt.Style.Add("display", "none");
                                    PCF.SetValuesforTransactionDocument("", dsInput, drTotals, ref bindtext, frmObj, strActualCtrlId, ref conobj, intCurrentRow, ref strBindRowID, droTemp);
                                }
                                //else
                                //{
                                //    SetHiddenValues(ref hf, frmObj);
                                //}
                            }

                        }

                        if (dsInput != null) // Check for Transaction Document page
                        {
                            UpdateAfrowidForTransactionDocumentPage(ref hf, dsInput, j); //Added for Transaction Document page af_row_id update
                        }


                        //if (frmMainObj != null) frmMainObj.Controls.Add(hf); //Orginal code

                        if (frmMainObj != null) // Added by srivatsan
                        {
                            if (dsInput != null)
                            {
                                if (frmMainObj.FindControl("ctl00$ContentPlaceHolder3$UpdatePanel1") != null)
                                {
                                    UpdatePanel panel = (UpdatePanel)frmMainObj.FindControl("ctl00$ContentPlaceHolder3$UpdatePanel1");
                                    //panel.Controls.Add(hf);
                                    panel.ContentTemplateContainer.Controls.Add(hf);
                                }

                                //frmMainObj.Controls.Add(txt);
                            }
                            else
                            {
                                if (droTemp["control_id"].ToString().Trim() == "af_row_id")
                                {
                                    if (HttpContext.Current.Request.QueryString["CPY"] != null || HttpContext.Current.Request.QueryString["PK"] == null)
                                    {
                                        ScreenReader SR = new ScreenReader();
                                        //hf.Value = SR.getHashKey();  //SRIVATSAN JUN 8 2010 FOR AFROWID TESTING
                                        SR = null;
                                    }
                                }
                                frmMainObj.Controls.Add(hf);
                            }
                        }
                        //if (frmMainObj.FindControl("ctl00$ContentPlaceHolder3$UpdatePanel1") != null)
                        //{
                        //    UpdatePanel panel = (UpdatePanel)frmMainObj.FindControl("ctl00$ContentPlaceHolder3$UpdatePanel1");
                        //    //panel.Controls.Add(hf);
                        //    panel.ContentTemplateContainer.Controls.Add(hf);
                        //}
                    }

                }
                bool bDelete = objSec.getObjectRightsForUser(droPage["object_id"].ToString(), "Delete");
                GeneratePageTable(arlHtmlCells, htaPageTable, droPage, intCurrentRow, intRowCnt, intStartFrom, bDelete, dscontrolevents, droPageCtrl, drTotals, dsInput); // modified by srivatsan for control events //changed by Dhanapal on Dec 08 2010
                //GeneratePageTable(arlHtmlCells, htaPageTable, droPage, intCurrentRow, intRowCnt, intStartFrom, bDelete, dscontrolevents, droPageCtrl, drTotals, dsInput, dtaPage); // modified by srivatsan for control events
            }
            if (dsInput != null) // If Transaction document page create total fields
            {
                Hashtable hshTotals = new Hashtable();
                intPosTotal = AddTotalFields(htaPageTable, droPageCtrl, drTotals, dtaPage, intRowCnt, frmMainObj, htaPageTable, ref hshTotals);
                if (htaPageTable != null)
                    AddTotalLabel(ref htaPageTable, intPosTotal);

                CreateTaxFields(dsTax, htaPageTable, intPosTotal, frmObj);
                CreateGrandTotalFields(dsTax, htaPageTable, intPosTotal, frmObj, hshTotals);

                SetEventsForTransDocTaxFields(dsTax, ref htaPageTable, strPageId);

                hshTotals = null;
            }
        }
        if (blnMultiplePage)
        {
            HtmlInputHidden hihObj = (HtmlInputHidden)FindControl(frmObj.Controls, "_sys" + strPageId + "_RowCount");
            hihObj.Value = intRowCnt.ToString();

        }

        if (intStartFrom == 0)
        {
            //intStartfrom value is 0, if it is called from dynamic page. If value is > 0 then no need to add
            //Adds the page table into the mail table
            HtmlTableCell htcMainCell = new HtmlTableCell();
            if (!HttpContext.Current.Request.Url.ToString().ToLower().Contains("transdoc.aspx"))
                htcMainCell.ID = "Page_details_cell"; // Added by 'Imran Gani' on 31-May-2013, to handle sections as tabs
            htcMainCell.Controls.Add(htaPageTable);
            HtmlTableRow htrMainObj = new HtmlTableRow();
            htrMainObj.Cells.Add(htcMainCell);
            htaMain.Rows.Add(htrMainObj);
        }

        return blnStatus;
    }


    private int AddTotalFields(HtmlTable ht, DataRow[] dr, DataRow[] totalfield, DataTable dtaPage, int rowcount, HtmlForm frm, HtmlTable htapagetable, ref Hashtable hshtotals)
    {
        HtmlTableRow htr = new HtmlTableRow();
        //htr.BgColor = "RED";
        HtmlTableCell htc = new HtmlTableCell();
        int inttotalfieldtext = 0;
        int ctrlcount = 0;
        //  htc.Align = "Right";
        try
        {
            if (totalfield.Length > 0)
            {
                htr.Controls.Add(htc);

                for (int i = 0; i < dr.Length; i++)
                {
                    htc = new HtmlTableCell();
                    //htc.ID = "td_trans_doc_sub_total_" + i;
                    for (int j = 0; j < totalfield.Length; j++)
                    {
                        if (Convert.ToBoolean(dr[i]["control_visible"].ToString()))
                        {
                            ctrlcount = ctrlcount + 1;
                        }
                        if (dr[i]["control_attrib_id"].ToString().ToLower() == totalfield[j]["attrib_id"].ToString().ToLower())
                        {
                            Label lbltotal = new Label();
                            lbltotal.CssClass = "controlLabelFont";
                            lbltotal.Text = "&nbsp;";
                            string actualattrib_id = totalfield[j]["attrib_id"].ToString();
                            string page_id = dtaPage.Rows[0]["page_id"].ToString();
                            //GetTotalAmount(dtaPage.Rows[0]["page_id"].ToString(), rowcount, frm, htapagetable);
                            //lbltotal.Text = totalfield[j]["attrib_id"].ToString();
                            //lbltotal.CssClass = "controlLabelFont";
                            lbltotal.ID = "total_" + page_id + "_" + actualattrib_id;
                            htc.Controls.Add(lbltotal);
                            htc.Align = "Right";

                            if (hshtotals != null) // To get the position where the grand total need to be added
                                if (!hshtotals.Contains(page_id + "_" + actualattrib_id))
                                    hshtotals.Add(page_id + "_" + actualattrib_id, ctrlcount);

                            inttotalfieldtext = ctrlcount;

                        }
                        if (Convert.ToBoolean(dr[i]["control_visible"].ToString()))
                        {
                            htc.ID = "td_trans_doc_sub_total_" + ctrlcount;
                            htr.Controls.Add(htc);
                        }

                    }
                    // htr.Controls.Add(htc);
                }

            }
            ht.Controls.Add(htr);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error Add Total Fields :" + ex.Message);
        }
        return inttotalfieldtext;
    }


    private void GetTotalAmount(string pageid, int rowcount, HtmlForm frmobj, HtmlTable htapagetable)
    {
        for (int i = 1; i < rowcount; i++)
        {
            TextBox txt = (TextBox)FindControl(frmobj.Controls, "p_pg_ctr_");

            TextBox txt1 = (TextBox)FindControl(frmobj.Controls, "ctl00_ContentPlaceHolder3_p_pg_ctr_control_seq_1");
            TextBox txt3 = (TextBox)FindControl(frmobj.Controls, "p_pg_ctr_control_seq_1");
            HtmlTable ht = (HtmlTable)FindControl(frmobj.Controls, "ctl00_ContentPlaceHolder3_tbl_p_pg_ctr");

            Control cn = (Control)htapagetable.FindControl("ctl00_ContentPlaceHolder3_p_pg_ctr_control_seq_1");

            if (frmobj.FindControl("ctl00_ContentPlaceHolder3_p_pg_ctr_control_bind_id_6") != null)
            {

            }
        }
    }

    private void UpdateAfrowidForTransactionDocumentPage(ref HiddenField hf, DataSet dsInput, int j)
    {
        if (hf.ID.Contains("af_row_id"))
        {
            ScreenReader SR = new ScreenReader();
            if (dsInput != null)
            {
                if (dsInput.Tables.Count > 0)
                {
                    if (dsInput.Tables[0].Rows.Count > 0)
                    {
                        try
                        {

                            hf.Value = dsInput.Tables[0].Rows[j]["af_row_id"].ToString();

                            if (dsInput.Tables[0].Rows[j]["af_row_id"].ToString() == "")
                            {
                                hf.Value = SR.getHashKey();
                            }
                        }
                        catch { }
                    }
                }
            }
            SR = null;
        }
    }

    private void AddRequiredFieldValuesToHiddenVariable(DataSet dsInput, HtmlForm frmObj, DataRow[] drPrKeys)
    {
        // Added by srivatsan for get required field values
        try
        {
            if (dsInput != null)
            {
                HiddenField hf = (HiddenField)FindControl(frmObj.Controls, "hfrequiredfield");
                if (hf != null)
                {
                    string sPrimaryAtt1 = "";
                    if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("transdoc.aspx"))
                    {
                        for (int k = 0; k < drPrKeys.Length; k++)
                        {
                            sPrimaryAtt1 += "," + drPrKeys[k]["attrib_id"].ToString() + ":" + drPrKeys[k]["attrib_name"].ToString() + ",";
                        }
                    }
                    hf.Value = sPrimaryAtt1;
                }
            }
        }
        catch
        {

        }
    }

    private void AddTransDocCaptions(HtmlTable htaPageTable, DataRow[] droPageCtrl, DataTable dtaPageKeys)
    {
        HtmlTableCell htc = new HtmlTableCell();
        //htc.Attributes.Add("class", "Dynamic_TransDocHtmlTableCell");
        htc.Width = "100%";
        HtmlTableRow htr = new HtmlTableRow();
        string masterdetailfield = "";
        //htc.Controls.Add(new LiteralControl("&nbsp;")); // Added for sequence number
        //htr.Controls.Add(htc);
        htc = new HtmlTableCell();
        htc.Controls.Add(new LiteralControl("&nbsp;"));
        htr.Controls.Add(htc);

        for (int i = 0; i < droPageCtrl.Length; i++)
        {
            if (droPageCtrl[i]["control_visible"].ToString().ToLower() == "true")
            {

                DataRow[] drr = dtaPageKeys.Select("attrib_id='" + droPageCtrl[i]["control_attrib_id"].ToString() + "'");
                if (drr.Length > 0)
                {
                    masterdetailfield = drr[0]["attrib_id"].ToString().ToLower();
                }
                htc = new HtmlTableCell();
                Label lblobj = new Label();
                lblobj.CssClass = "controlLabelFont";
                lblobj.ID = "lb_" + droPageCtrl[i]["control_attrib_id"].ToString();
                lblobj.Text = droPageCtrl[i]["control_name"].ToString() + "&nbsp;";
                if (droPageCtrl[i]["control_attrib_id"].ToString().ToLower() == masterdetailfield || droPageCtrl[i]["control_attrib_id"].ToString().ToLower() == "owner_id")
                {
                    lblobj.Visible = false;
                }


                htc.Controls.Add(lblobj);
                htc.Attributes.Add("class", "Grid_Header_Cell");
                htr.Controls.Add(htc);
            }
        }
        //htc = new HtmlTableCell();
        //htc.Controls.Add(htr);
        htaPageTable.Controls.Add(htr);

    }

    public DataRow[] getTotalFields(string pageid)
    {
        DataSet ds = new DataSet();
        DataRow[] dr = null;
        try
        {
            string sql = "select * from sy_trans_doc_totals where page_id = '" + pageid + "'";
            ds = HDD.GetDataset(sql);

            dr = ds.Tables[0].Select();

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error getTotalFields :" + ex.Message);
        }
        return dr;
    }

    // Commented by srivatsan on OCt 26 2009 for Transaction Document changes
    //public bool LoadPageMember(DataTable dtaPage, HtmlForm frmObj, HtmlTable htaMain, DataRow[] droPageCtrl,
    //    DataTable dtaPageKeys, int intPageSeq, int intStartFrom, int intRowCnt)
    //{
    //    bool blnStatus = true;
    //    DataRow droTemp;
    //    HtmlTableCell htc;
    //    string strCtrlDesc = "";
    //    int intCurrentRow = 0;
    //    string strCtrlId = "";
    //    string strCtrlColumn = "";
    //    string strBindRowID = "";
    //    string strActualCtrlId = "";
    //    string strCtrlWidth = "";
    //    string sAttrib_Size = "";
    //    string sInputFormatMask = "";
    //    htc = new HtmlTableCell();
    //    DataRow droPage = dtaPage.Rows[intPageSeq];
    //    ArrayList arlHtmlCells = new ArrayList();
    //    string strMenuRowId = "";
    //    HDDatabase hdd = new HDDatabase();
    //    security objSec = new security();
    //    PageInfoLoad PIL = new PageInfoLoad();

    //    // Srivatsan May 15 2009 Control events 
    //    DataSet dscontrolevents = new DataSet();
    //    dscontrolevents = dsePageInfoMain;


    //    if (frmObj.Page.Request.QueryString["mn"].ToString() != null)
    //    {
    //        strMenuRowId = frmObj.Page.Request.QueryString["mn"].ToString();
    //    }
    //    if (intStartFrom == 0)
    //    {
    //        PageHeaderAdd(htaMain, droPage, strMenuRowId, objSec);
    //    }
    //    PageTooltipAdd(htaMain, droPage);//implemented by sanal on July 28, 2008
    //    string strPageId = dtaPage.Rows[intPageSeq]["page_id"].ToString();

    //    bool blnMultiplePage = Convert.ToBoolean(dtaPage.Rows[intPageSeq]["multiple_recs_page"].ToString());
    //    bool blnFirstRowCaptionOnly = false;
    //    if (dtaPage.Rows[intPageSeq]["first_row_caption_only"] == DBNull.Value)
    //    {
    //        blnFirstRowCaptionOnly = GlobalValues.FirstRowCaptionOnly;
    //    }
    //    else
    //    {
    //        blnFirstRowCaptionOnly = Convert.ToBoolean(dtaPage.Rows[intPageSeq]["first_row_caption_only"].ToString());
    //    }
    //    //string strPageId = dtaPage.Rows[intPageSeq]["page_id"].ToString();
    //    HtmlTable htaPageTable = new HtmlTable();
    //    if (intStartFrom > 0)
    //    {
    //        htaPageTable = (HtmlTable)FindControl(frmObj.Controls, "tbl_" + strPageId);//htaPageTable = (HtmlTable)frmObj.FindControl("tbl_" + strPageId);
    //    }
    //    htaPageTable.Attributes.Add("width", "100%");
    //    htaPageTable.ID = "tbl_" + strPageId;
    //    htaPageTable.CellPadding = 0;
    //    htaPageTable.CellSpacing = 0;
    //    htaPageTable.Border = 0;

    //    if (blnMultiplePage)
    //    {
    //        if (FindControl(frmObj.Controls, "_sys" + strPageId + "_RowCount") == null)
    //        {
    //            HtmlInputHidden hihObj = new HtmlInputHidden();
    //            hihObj.ID = "_sys" + strPageId + "_RowCount";
    //            frmObj.Controls.Add(hihObj);
    //        }
    //    }
    //    bool blnSeqControl = false;
    //    bool blnCaption = true;
    //    string strPageView = "";
    //    if (droPage["page_view"] == DBNull.Value)
    //    {
    //        strPageView = GlobalValues.DefaultPageView;
    //    }
    //    else
    //    {
    //        strPageView = droPage["page_view"].ToString();
    //    }

    //    if (checkRightsForObject(htaPageTable, objSec, strPageId, droPage["object_id"].ToString(), "read") == true) 
    //    {
    //        Hashtable hsControlValues = new Hashtable();
    //        //if (!frmObj.Page.IsPostBack)
    //        //{
    //            DataSet dsPageEvents = PIL.pageEventHandler(strPageId);

    //            if (dsPageEvents != null)
    //            {
    //                DataSet dsPageInfo = dtaPage.DataSet.Copy(); ;
    //                if (dsPageEvents.Tables.Count > 0)
    //                    PIL.triggerEvent(dsPageEvents, "PL", ref hsControlValues, ref dsPageInfo, frmObj);
    //                dsPageInfo.Dispose();
    //                dsPageInfo = null;
    //            }
    //        //}

    //        //////string sSql = "select attrib_id from sy_obj_att obj_att inner join sy_obj obj on obj.af_row_id=obj_att.object_id where obj.object_id='" + droPage["object_id"].ToString().Replace("'", "''") + "' and obj_att.is_key='true'";
    //        //////string sKeyAtt = hdd.GetColumnValue(sSql);
    //        DataTable dtObjatt = new DataTable();
    //        //string sSql = "select attrib_id from sy_obj_att obj_att inner join sy_obj obj on obj.af_row_id=obj_att.object_id where obj.object_id='" + droPage["object_id"].ToString().Replace("'", "''") + "' and obj_att.is_key='true'";
    //        string sSql = "select attrib_id,is_key,is_primary,object_tooltip from sy_obj_att obj_att inner join sy_obj obj on obj.af_row_id=obj_att.object_id where obj.object_id='" + droPage["object_id"].ToString().Replace("'", "''") + "'";
    //        //string sSql = "select attrib_id,is_key,is_primary from sy_obj_att obj_att object_id='" + droPage["object_id"].ToString().Replace("'", "''") + "'";
    //        dtObjatt = hdd.GetDataTable(sSql);
    //        string sKeyAtt = ""; string sPrimaryAtt = ""; string sRelationalField = ""; Hashtable Tooltips = new Hashtable();
    //        foreach (DataRow dr in dtObjatt.Rows)
    //            Tooltips.Add(dr["attrib_id"].ToString(), dr["object_tooltip"].ToString());
    //        try
    //        {
    //            DataRow[] drKeys = dtObjatt.Select("is_key='true'");
    //            if (drKeys.Length>0)
    //                sKeyAtt = drKeys[0]["attrib_id"].ToString();
    //            DataRow[] drPrKeys = dtObjatt.Select("is_primary='true'");
    //            for (int k = 0; k < drPrKeys.Length; k++)
    //                sPrimaryAtt +=  "," + drPrKeys[k]["attrib_id"].ToString() + ",";
    //            //sPrimaryAtt = dtObjatt.Select("is_primary='true'")[0]["attrib_id"].ToString();
    //        }
    //        catch(Exception e){}                       
    //        dtObjatt = null;

    //        sRelationalField = isRelationalField(droPage["object_id"].ToString().Replace("'", "''"));

    //        bool bEdit = objSec.getObjectRightsForUser(droPage["object_id"].ToString(), "Edit") || objSec.getObjectRightsForUser(droPage["object_id"].ToString(), "Create");
    //        //string datetimscript = "";
    //        for (int j = intStartFrom; j < intRowCnt; j++)
    //        {
    //            arlHtmlCells = new ArrayList();
    //            intCurrentRow = j + 1;
    //            //if control caption repeat is false and control row is greater than 1 then no need to add the caption
    //            if (blnFirstRowCaptionOnly)
    //            {
    //                if (j > 0)
    //                {
    //                    blnCaption = false;
    //                }
    //            }

    //            for (int i = 0; i < droPageCtrl.Length; i++)
    //            {
    //                droTemp = droPageCtrl[i];
    //                /////strActualCtrlId = droTemp["control_id"].ToString(); //used for passing into control_init method
    //                /////strCtrlId = droTemp["control_id"].ToString();
    //                /////j
    //                strActualCtrlId = droTemp["control_attrib_id"].ToString();
    //                strCtrlId = droTemp["control_attrib_id"].ToString();

    //                strBindRowID = droTemp["control_bind_id"].ToString();
    //                strCtrlWidth = droTemp["control_width"].ToString();
    //                sAttrib_Size = droTemp["attrib_size"].ToString();
    //                if (droTemp.Table.Columns.Contains("input_mask_format"))
    //                    sInputFormatMask = droTemp["input_mask_format"].ToString();
    //                strCtrlId = strPageId + "_" + strCtrlId;
    //                string sIsKey = "false"; string sIsPrimary = "false"; string sIsRelationalField = "false";
    //                if (strActualCtrlId.ToLower() == sKeyAtt.ToLower())
    //                    sIsKey = "true";
    //                //if (strActualCtrlId.ToLower() == sPrimaryAtt.ToLower())
    //                if (sPrimaryAtt.ToLower().IndexOf("," + strActualCtrlId.ToLower() + ",")>-1)
    //                    sIsPrimary = "true";
    //                if (sRelationalField.ToLower().IndexOf("," + strActualCtrlId.ToLower() + ",") > -1)
    //                    sIsRelationalField = "true";



    //                //DataSet ds = droTemp.Table.DataSet;

    //                if (droTemp.Table.Columns.Contains("read_only"))
    //                    if (droTemp["read_only"] != System.DBNull.Value)
    //                        bEdit = !Convert.ToBoolean(droTemp["read_only"].ToString());

    //                if (blnMultiplePage)
    //                    strCtrlId += "_" + intCurrentRow.ToString();

    //                if (droTemp["is_seq_control"] != System.DBNull.Value)
    //                    blnSeqControl = (Convert.ToBoolean(droTemp["is_seq_control"].ToString()));

    //                if (droTemp["control_html"].ToString() != "HI" && Convert.ToBoolean(droTemp["control_visible"].ToString() == "" ? "false" : droTemp["control_visible"].ToString()) != false)
    //                {
    //                    strCtrlDesc = droTemp["control_name"].ToString();
    //                    strCtrlColumn = droTemp["control_attrib_id"].ToString();
    //                    /*if (PCF.IsParentPageKeyControl(strCtrlColumn, dtaPage, dtaPageKeys, intPageSeq) == false)
    //                    {*/
    //                        string sObject_id = dtaPage.Rows[0]["object_id"].ToString();
    //                        string strCtrlHtml = droTemp["control_html"].ToString();
    //                        string strDefaultVal = droTemp["default_value"].ToString();

    //                        if (hsControlValues.Contains("[" + sObject_id + "].[" + strActualCtrlId + "]"))
    //                            strDefaultVal = Convert.ToString(hsControlValues["[" + sObject_id + "].[" + strActualCtrlId + "]"]);

    //                        //string sSql = "select is_key from sy_obj_att where object_id='" + droPage["object_id"].ToString().Replace("'", "''") + "' and attrib_id='" + droTemp["control_attrib_id"].ToString().Replace("'", "''") + "'";
    //                        //string sIsKey = hdd.GetColumnValue(sSql);

    //                        if (HttpContext.Current.Request.QueryString["VMODE"] != null)
    //                            if (HttpContext.Current.Request.QueryString["VMODE"] == "1")
    //                                bEdit = false;//strCtrlHtml = "";

    //                        string sToolTip = getValueFromKey(Tooltips,strCtrlColumn);
    //                        addSection(ref arlHtmlCells, strPageView, droTemp,droPage);//implemented by sanal on 22Aug2008 to add sections in the controls rendered
    //                        PCF.ControlInit(htc, intCurrentRow, strPageView, strCtrlId, strCtrlDesc, strBindRowID, strCtrlHtml, arlHtmlCells,
    //                            blnSeqControl, BC, strDefaultVal, blnCaption, strActualCtrlId, strCtrlWidth, sObject_id, sIsKey.ToLower(),sIsPrimary.ToLower(), blnMultiplePage, bEdit, sAttrib_Size,droTemp, dtaPageKeys,sIsRelationalField,sToolTip,sInputFormatMask);
    //                        /*
    //                         * removed all the control case and moved to page common function
    //                         * for better followup
    //                        */
    //                    //}
    //                }
    //                if (droTemp["control_html"].ToString() == "HI" && Convert.ToBoolean(droTemp["control_visible"].ToString()) == true)
    //                {
    //                    HtmlInputHidden hihObj = new HtmlInputHidden();
    //                    hihObj.ID = strCtrlId;
    //                    frmObj.Controls.Add(hihObj);
    //                }
    //                //if (droTemp["control_attrib_id"].ToString() == "af_row_id")
    //                if (!Convert.ToBoolean(droTemp["control_visible"].ToString() == "" ? "false" : droTemp["control_visible"].ToString()))
    //                {
    //                    HiddenField hf = new HiddenField();
    //                    hf.ID = strCtrlId;

    //                    if (HttpContext.Current.Request.QueryString["PK"] == null)
    //                    {
    //                        if (HttpContext.Current.Request.QueryString["pgs_id"] != null)
    //                        {
    //                            if (HttpContext.Current.Request.QueryString["pgs_id"].ToString().ToLower() == "ps_notes")
    //                            {
    //                                hf.Value = GetNotesHiddenFieldData(strCtrlId, dsePageInfoMain);
    //                            }
    //                            else
    //                            {
    //                                if (droTemp.Table.Columns.Contains("default_value"))
    //                                    hf.Value = droTemp["default_value"].ToString();
    //                            }
    //                        }
    //                    }
    //                    else
    //                    {
    //                        if (droTemp.Table.Columns.Contains("default_value"))
    //                            hf.Value = droTemp["default_value"].ToString();
    //                    }


    //                    if (frmMainObj!=null) frmMainObj.Controls.Add(hf);
    //                }

    //            }                
    //            bool bDelete = objSec.getObjectRightsForUser(droPage["object_id"].ToString(), "Delete");
    //            GeneratePageTable(arlHtmlCells, htaPageTable, droPage, intCurrentRow, intRowCnt, intStartFrom, bDelete, dscontrolevents); // modified by srivatsan for control events
    //        }                        
    //    }        
    //    if (blnMultiplePage)
    //    {
    //        HtmlInputHidden hihObj = (HtmlInputHidden)FindControl(frmObj.Controls, "_sys" + strPageId + "_RowCount");
    //        hihObj.Value = intRowCnt.ToString();
    //    }

    //    if (intStartFrom == 0)
    //    {
    //        //intStartfrom value is 0, if it is called from dynamic page. If value is > 0 then no need to add
    //        //Adds the page table into the mail table
    //        HtmlTableCell htcMainCell = new HtmlTableCell();
    //        htcMainCell.Controls.Add(htaPageTable);
    //        HtmlTableRow htrMainObj = new HtmlTableRow();
    //        htrMainObj.Cells.Add(htcMainCell);
    //        htaMain.Rows.Add(htrMainObj);
    //    }

    //    return blnStatus;
    //}
    private void addSection(ref ArrayList arlHtmlCells, string strPageView, DataRow droPageControl, DataRow droPage, ref ArrayList arlsectionDistinctName )//implemented by sanal on 22 Aug 2008
    {
        //validations

        /***Added By dhanapal for sectionname**************/
        if (droPageControl.Table.Columns.Contains("section_name"))
        {
            if (droPageControl["section_name"].ToString().ToLower() != "")
            {
                string strSecName = droPageControl["section_name"].ToString();
                addDistinctSectionNameCell(ref  arlsectionDistinctName, strSecName, ref arlHtmlCells, droPage, strPageView);
            }
        }
        /**************************************************/
        if (!droPageControl.Table.Columns.Contains("is_section")) return;
        if (droPageControl["is_section"].ToString().ToLower() == "false") return;
        if (droPageControl["is_section"].ToString().ToLower() == "0") return;
        if (droPageControl["is_section"].ToString().ToLower() == "") return;

        int intRowCtrlCnt = 0; int cellsInNewRow = 0;
        if (droPage["control_per_row"].ToString() == "")
            intRowCtrlCnt = GlobalValues.DefaultControlPerRow;
        else
            intRowCtrlCnt = Convert.ToInt32(droPage["control_per_row"].ToString());
        int multiFactor = 1;
        if (strPageView == "2") multiFactor = 2;//cells gets doubled in this case
        cellsInNewRow = arlHtmlCells.Count % (intRowCtrlCnt * multiFactor);//find the cells in new row
        if (cellsInNewRow == 0) return;//if the cell is the first element, don't put a break
        cellsInNewRow = (intRowCtrlCnt * multiFactor) - cellsInNewRow;//calculates the no of blank cells to generate

        for (int i = 0; i < cellsInNewRow; i++)//create blank cells and add
        {
            HtmlTableCell ht = new HtmlTableCell();
            ht.Controls.Add(new LiteralControl("&nbsp;"));
            arlHtmlCells.Add(ht);
           
        }


    }

    private void addDistinctSectionNameCell(ref ArrayList arlSectionDistinctName, string strSectionName, ref ArrayList arlHtmlCells, DataRow droPage, string strPageView)//added By Dhanapal
    {
        bool issectionpresent = false;  //Added By Dhanapal To Prevent Case sensitive On Dec 16 2010
        foreach (String secname in arlSectionDistinctName)
        {
            if (secname.ToLower() == strSectionName.ToLower())
            {
                issectionpresent = true;
            }
        }
       
        // if (!arlSectionDistinctName.Contains(strSectionName))//Previous Code By Dhanapal On Dec 09 2010
        if(!issectionpresent)
        {
            arlSectionDistinctName.Add(strSectionName);
            int intRowCtrlCnt = 0; int cellsInNewRow = 0;
            if (droPage["control_per_row"].ToString() == "")
                intRowCtrlCnt = GlobalValues.DefaultControlPerRow;
            else
                intRowCtrlCnt = Convert.ToInt32(droPage["control_per_row"].ToString());
            int multiFactor = 1;
            if (strPageView == "2") multiFactor = 2;//cells gets doubled in this case
            cellsInNewRow = arlHtmlCells.Count % (intRowCtrlCnt * multiFactor);//find the cells in new row
            //if (cellsInNewRow == 0) return;//if the cell is the first element, don't put a break
            if (cellsInNewRow != 0) //If the sell is the First Element
            {
                cellsInNewRow = (intRowCtrlCnt * multiFactor) - cellsInNewRow;//calculates the no of blank cells to generate
                for (int i = 0; i < cellsInNewRow; i++)//create blank cells and add
                {
                    HtmlTableCell ht = new HtmlTableCell();
                    ht.Controls.Add(new LiteralControl("&nbsp;"));
                    arlHtmlCells.Add(ht);
                   
                }
            }
            int intTotalRowCount = 0;
            intTotalRowCount = intRowCtrlCnt * multiFactor;
            for (int i = 0; i < intTotalRowCount; i++)//create blank cells and add
            {
                HtmlTableCell ht = new HtmlTableCell();
                if (i == 0)
                {
                    ht.ID = "pe_sectionheader_" + strSectionName;
                    ht.Controls.Add(new LiteralControl("pe_sectionheader_" + strSectionName));

                }
                else
                {
                    ht.Controls.Add(new LiteralControl("&nbsp;"));
                }
                
                arlHtmlCells.Add(ht);
            }

        }

    }
    public string getValueFromKey(Hashtable ht, string keyName)
    {
        try
        {
            if (ht.ContainsKey(keyName))
                return ht[keyName].ToString();
            return "";
        }
        catch (Exception e)
        {
            return "";
        }
    }
    private bool isViewMode()
    {
        if (HttpContext.Current.Request.QueryString["VMODE"] != null)
            if (HttpContext.Current.Request.QueryString["VMODE"] == "1")
                return false;
        return true;
    }

    public string getDateValues(string strFldValue, bool convertToUniversal)
    {
        try
        {
            if (convertToUniversal)
                return DateTime.Parse(strFldValue, System.Globalization.CultureInfo.InvariantCulture).ToUniversalTime().ToString();
            if (HttpContext.Current.Request.QueryString["PK"] == null)
                return DateTime.Parse(strFldValue, System.Globalization.CultureInfo.InvariantCulture).ToUniversalTime().ToString();
            else
                return DateTime.Parse(strFldValue, System.Globalization.CultureInfo.InvariantCulture).ToString();
        }
        catch (Exception e)
        {
            return strFldValue;
        }
    }

    public string getUserSetting(string SourceTableName, string SourceFieldName, string LookupTableName, string LookupFieldName, string MappingFieldName)
    {
        string sValue = "";
        try
        {
            sValue = CommonFunctions.GetColValueFromPageInfo((HttpContext.Current.Request.QueryString["pgs_id"] == null ? "" : HttpContext.Current.Request.QueryString["pgs_id"].ToString()), SourceTableName, SourceFieldName, "user_id = '" + HttpContext.Current.Session["userid"].ToString().Replace("'", "''") + "'");
            if (sValue == "") sValue = HDD.GetColumnValue(SourceTableName, SourceFieldName, "user_id = '" + HttpContext.Current.Session["userid"].ToString().Replace("'", "''") + "'");

            if (sValue != "")
            {
                sValue = HDD.GetColumnValue(LookupTableName, LookupFieldName, MappingFieldName + "='" + sValue + "'");
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : getUserSetting : " + ex.Message);
            sValue = "";
        }
        return sValue;
    }
    public ArrayList getUserSetting(string SourceTableName, string SourceFieldName, string LookupTableName, ArrayList LookupFieldNames, string MappingFieldName)
    {
        ArrayList ret = new ArrayList();
        if (LookupFieldNames.Count < 1) return ret;
        string sValue = ""; string temp = "";
        try
        {
            sValue = CommonFunctions.GetColValueFromPageInfo((HttpContext.Current.Request.QueryString["pgs_id"] == null ? "" : HttpContext.Current.Request.QueryString["pgs_id"].ToString()), SourceTableName, SourceFieldName, "user_id = '" + HttpContext.Current.Session["userid"].ToString().Replace("'", "''") + "'");
            if (sValue == "") sValue = HDD.GetColumnValue(SourceTableName, SourceFieldName, "user_id = '" + HttpContext.Current.Session["userid"].ToString().Replace("'", "''") + "'");

            if (sValue != "")
            {
                for (int i = 0; i < LookupFieldNames.Count; i++)
                    temp = temp + LookupFieldNames[i].ToString() + ",";
                temp = temp.TrimEnd(',');
                DataTable dt = HDD.GetDataTable("select " + temp + " from " + LookupTableName + " where " + MappingFieldName + "='" + sValue + "'");
                if (dt != null)
                {
                    foreach (DataColumn dc in dt.Columns)
                        ret.Add(dt.Rows[0][dc.ColumnName].ToString());
                }
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : getUserSetting : " + ex.Message);
        }
        return ret;
    }
    public string manageCurrency(string originalValue, ArrayList currencyCode)
    {
        if (currencyCode.Count < 1) return originalValue;
        if (currencyCode.Count < 2)
        {
            LogWriter.WriteLog("No Corporate currency defined.");
            return originalValue;
        }
        string ret = originalValue; Double inputValue = 0;
        double conversionRate = 0; double temp = 0; double corporate = 0;
        corporate = double.Parse(currencyCode[2].ToString());
        try
        {
            inputValue = originalValue == "" ? 0 : double.Parse(originalValue);
            conversionRate = currencyCode[0].ToString() == "" ? 1 : double.Parse(currencyCode[0].ToString());
            temp = (inputValue * corporate) / conversionRate;
            // ret = currencyCode[1] + " " + getValueInUserCurrency(temp); //temp.ToString("#0.00"); // commanded by 'Imran Gani' on 09-Aug-12.
            ret = getValueInUserCurrency(temp); // Added by 'Imran Gani' on 09-Aug-12.
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("manageCurrency : Error : " + e.Message);
        }
        return ret;
    }
    private string getValueInUserCurrency(double e)
    {
        string ret = "";
        #region Old code commented by 'Imran Gani' on 28-Feb-2014, for locale support
        //Localization ll = new Localization();
        //ret = ll.getUserCurrencyCode() + " " + ll.getUserCurrency(e); // Modified by 'Imran Gani' on 09-Aug-12, for currency format.
        //ll = null;
        #endregion
        string sLocale = HttpContext.Current.Session["userlocale"].ToString();
        ret = MBLocalization.getCurrencyCode(sLocale) + " " + MBLocalization.getLocalizedDecimal(sLocale, e);
        return ret;
    }
    public double getCorporateCurrency()
    {
        try
        {
            DataSet ds = new DataSet();
            //ds = HDD.GetDataset("select c_rate from sy_currency where c_iscorporate='True'");
            ds = HDD.GetDataset("select c_rate from sy_currency where c_iscorporate=1");
            if (ds != null)
                return double.Parse(ds.Tables[0].Rows[0][0].ToString());
            else
                return 1.0;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("manageCurrency : Error : " + e.Message);
        }
        return 1.0;
    }
    #region Old code commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
    //private string getDTFormat4user()//implemented by sanal on Sept 02, 2008
    //{
    //    //string ret="";
    //    //    CultureInfo ci = new CultureInfo("fr-FR");
    //    //    ret = ci.DateTimeFormat.ShortDatePattern();
    //    //    ci = null;
    //    //    return ret;
    //    Localization ll = new Localization();
    //    string ret = ll.getDateFormat() + " hh:mm tt";
    //    ll = null;
    //    return ret;
    //    //return "dd-MMM-yyyy hh:mm tt";
    //}
    #endregion
    public string getUsersDT(string Value, string sUTC_Offset)
    {
        string ret = "";
        Localization ll = new Localization();
        ret = ll.getDateTime4TimeZone(Value, sUTC_Offset, false, false);
        ll = null;
        return ret;
        #region Old code commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
        //string sValue = "";
        //string sDateTimeFormatString = getDTFormat4user();// "dd-MMM-yyyy hh:mm tt";
        ////DateTime dt1 = DateTime.Parse(Value, System.Globalization.CultureInfo.InvariantCulture);
        ////return dt1.ToLocalTime().ToString(sDateTimeFormatString);
        //try
        //{
        //    string sHours = "";
        //    string sMinutes = "";
        //    if (Value == "") return Value;
        //    if (sUTC_Offset != "")
        //    {
        //        if (sUTC_Offset.IndexOf('.') != -1)
        //        {
        //            sHours = sUTC_Offset.Substring(1, sUTC_Offset.IndexOf('.') - 1);
        //            sMinutes = sUTC_Offset.Substring(sUTC_Offset.IndexOf('.') + 1, sUTC_Offset.Length - sUTC_Offset.IndexOf('.') - 1);
        //        }
        //        else
        //            sHours = sUTC_Offset.Substring(1, sUTC_Offset.Length - 1);

        //        if (sUTC_Offset.StartsWith("-"))
        //        {
        //            sHours = "-" + sHours;
        //            if (sMinutes != "")
        //                sMinutes = "-" + sMinutes;
        //        }
        //    }
        //    if (sHours == "") sHours = "0";

        //    DateTime dt = DateTime.Parse(Value, System.Globalization.CultureInfo.InvariantCulture); //DateTime.Parse(Value);//sanal on Sept 04, 2008
        //    dt = dt.AddHours(Convert.ToDouble(sHours));
        //    if (sMinutes != "")
        //        dt = dt.AddMinutes(Convert.ToDouble(sMinutes));
        //    sValue = dt.ToLocalTime().ToString(sDateTimeFormatString); //dt.ToString(sDateTimeFormatString);//sanal on Sept 04, 2008
        //}

        //catch (Exception ex)
        //{
        //    LogWriter.WriteLog("getUsersDT : Error : " + ex.Message);
        //    sValue = Value;
        //}
        //return sValue;
        #endregion
    }

    public string getGMT(string Value, string sUTC_Offset)
    {
        string sValue = "";
        string sDateTimeFormatString = "dd-MMM-yyyy hh:mm tt";
        try
        {
            string sHours = "";
            string sMinutes = "";
            if (Value == "") return Value;
            if (sUTC_Offset != "")
            {
                if (sUTC_Offset.IndexOf('.') != -1)
                {
                    sHours = sUTC_Offset.Substring(1, sUTC_Offset.IndexOf('.') - 1);
                    sMinutes = sUTC_Offset.Substring(sUTC_Offset.IndexOf('.') + 1, sUTC_Offset.Length - sUTC_Offset.IndexOf('.') - 1);
                }
                else
                    sHours = sUTC_Offset.Substring(1, sUTC_Offset.Length - 1);

                if (sUTC_Offset.StartsWith("-"))
                {
                    sHours = "-" + sHours;
                    if (sMinutes != "")
                        sMinutes = "-" + sMinutes;
                }
            }
            if (sHours == "") sHours = "0";

            DateTime dt = DateTime.Parse(Value);
            dt = dt.AddHours(Convert.ToDouble("-" + sHours));
            if (sMinutes != "")
                dt = dt.AddMinutes(Convert.ToDouble("-" + sMinutes));
            sValue = dt.ToString();
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getUsersDT : Error : " + ex.Message);
            sValue = Value;
        }
        return sValue;
    }

    public string getUsersDateTime(string Value)
    {
        string sValue = "";
        try
        {
            string sUTC_Offset = getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");

            sValue = getUsersDT(Value, sUTC_Offset);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getUsersDT : Error : " + ex.Message);
            sValue = Value;
        }
        return sValue;
    }


    private bool GeneratePageTable(ArrayList arlHtmlCells, HtmlTable htaPageTable, DataRow droPage, int intCurrentRow, int intTotalRow, int intStartFrom, bool Delete, DataSet dsControlEvents, DataRow[] droPageCtrl, DataRow[] drtotals, DataSet dsInput)
    {
        CommonFunctions comm = new CommonFunctions();
        bool blnStatus = true;
        bool blnMultiplePage = Convert.ToBoolean(droPage["multiple_recs_page"].ToString());
        string strPageId = droPage["page_id"].ToString();
        string strPageView = "";

        DataRow[] drcontrolevents = null;

        //drisvisibleControls = droPageCtrl.

        if (dsControlEvents != null)   // Added by srivatsan for control events
        {
            if (dsControlEvents.Tables.Count > 0)
            {
                if (dsControlEvents.Tables.Contains("ControlEvents"))//ssks
                {
                    if (dsControlEvents.Tables["ControlEvents"].Rows.Count > 0)
                    {
                        drcontrolevents = dsControlEvents.Tables["ControlEvents"].Select();
                    }
                }
            }
        }//


        if (droPage["page_view"] == DBNull.Value)
        {
            strPageView = GlobalValues.DefaultPageView;
        }
        else
        {
            strPageView = droPage["page_view"].ToString();
        }
        int intRowCtrlCnt = 0;
        if (droPage["control_per_row"] == DBNull.Value)
        {
            intRowCtrlCnt = GlobalValues.DefaultControlPerRow;
        }
        else
        {
            intRowCtrlCnt = Convert.ToInt32(droPage["control_per_row"].ToString());
        }

        if (strPageView == "2")
        {
            intRowCtrlCnt = intRowCtrlCnt * 2;
        }

        if (intStartFrom > 0 && intCurrentRow == 2 && isViewMode() && Delete)
        {
            if (dsInput != null)
            {
                // Transaction document page
                ImageButton btnRemoveObj = new ImageButton();
                btnRemoveObj.ID = "btn_" + strPageId + "_Remove_1";
                btnRemoveObj.CausesValidation = false;
                //btnRemoveObj.Text = "Remove";  //srivatsan
                btnRemoveObj.ImageUrl = "Images/delete.GIF";
                btnRemoveObj.ToolTip = "Delete";
                //btnRemoveObj.Click += new EventHandler(btnRemoveObj_Click); // srivatsan
                btnRemoveObj.Click += new ImageClickEventHandler(btnRemoveimgObj_Click);
                btnRemoveObj.OnClientClick = "javascript:updateclickstatus('del'); return RemoveRow('" + strPageId + "','1')";//btnRemoveObj.OnClientClick = "return RemoveRow('" + strPageId + "','1" + intCurrentRow.ToString() + "')";
                htaPageTable.Rows[htaPageTable.Rows.Count - 1].Cells[intRowCtrlCnt + 1].Controls.Clear();
                htaPageTable.Rows[htaPageTable.Rows.Count - 1].Cells[intRowCtrlCnt + 1].Controls.Add(btnRemoveObj);
            }
            else
            {
                Button btnRemoveObj = new Button();
                btnRemoveObj.ID = "btn_" + strPageId + "_Remove_1";
                btnRemoveObj.Text = "Remove";
                btnRemoveObj.Click += new EventHandler(btnRemoveObj_Click);
                //btnRemoveObj.OnClientClick = "return RemoveRow('" + strPageId + "','1')";//btnRemoveObj.OnClientClick = "return RemoveRow('" + strPageId + "','1" + intCurrentRow.ToString() + "')";
                btnRemoveObj.OnClientClick = "javascript:RemoveRow('" + strPageId + "','1'); __doPostBack('" + btnRemoveObj.ID + "','');";
                btnRemoveObj.UseSubmitBehavior = false;
                //if (strPageView == "1")
                //{
                htaPageTable.Rows[htaPageTable.Rows.Count - 1].Cells[intRowCtrlCnt + 1].Controls.Clear();
                htaPageTable.Rows[htaPageTable.Rows.Count - 1].Cells[intRowCtrlCnt + 1].Controls.Add(btnRemoveObj);
                /*}
                if (strPageView == "2")
                {
                    htaPageTable.Rows[htaPageTable.Rows.Count - 1].Cells[(intRowCtrlCnt*2) + 1].Controls.Clear();
                    htaPageTable.Rows[htaPageTable.Rows.Count - 1].Cells[(intRowCtrlCnt * 2) + 1].Controls.Add(btnRemoveObj);
                }*/
            }

        }
        string strSectionName = string.Empty; //Added By Dhanapal To get The Section NAme on Dec 09 2010
        bool blnmultipageflag = false; //Added  By Dhanapal on Dec 10 2010
        for (int i = 0; i < arlHtmlCells.Count; i = i + intRowCtrlCnt)
        {
            //System.Web.UI.LiteralControl
            /********Added By Dhanapal For Section Header 25 Nov 2010***************/
           

            HtmlTableCell ccell = (HtmlTableCell)arlHtmlCells[i];
            if (ccell.Controls.Count == 1)
            {
                if (checkandAppendSectionHeader(ref  htaPageTable, intRowCtrlCnt, intCurrentRow.ToString(), ccell, ref strSectionName)) 
                {
                    if (blnMultiplePage && i == 0) //Changes Done On Dec 10 2010 For Multi Section BY Dhanapal
                    {
                        blnmultipageflag = true;
                    }

                    continue;
                }
                
            }
            /******End of the Code Change*************/
            HtmlTableRow htrObj = new HtmlTableRow();
            HtmlTableCell htc = new HtmlTableCell();
            if (blnmultipageflag)//Changes Dec 10 2010 Dhanapal
            {
                htc.Controls.Add(new LiteralControl(intCurrentRow.ToString()));
                blnmultipageflag = false;
            }
            else
            {
                htc.Controls.Add(new LiteralControl("&nbsp;")); //change nov 26 2010

            }
            htrObj.ID = comm.RemoveSpecialCharacters(strSectionName) + "_" + intCurrentRow + "__Child" + i; //Added By Dhanapal To Maintain Tr Id on Dec 09 2010 // Modified by 'Imran Gani' on 24-Jun-2013, to handle special characters
            htrObj.Cells.Add(htc);
          

            for (int j = i; j < i + intRowCtrlCnt; j++)
            {
                htc = new HtmlTableCell();
                if (j < arlHtmlCells.Count)
                {
                    htc = (HtmlTableCell)arlHtmlCells[j];

                    AssignTotalFieldEvents(ref htc, drtotals, strPageId);
                    SetEventsforControl(ref htc, drcontrolevents, strPageId);  // Added by srivatsan for control events

                    if (dsInput == null) // Added for transaction document header section
                    {
                        if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("transdoc.aspx"))
                        {
                            if (htc.Controls.Count > 0)  // Added by srivatsan for Header right alignments
                            {

                                int cntrlcount = htc.Controls.Count;
                                if (strPageView == "1")
                                {
                                    // for (int k = 0; k < cntrlcount; k++)
                                    //{
                                    HtmlTable htmltable1 = new HtmlTable();
                                    htmltable1.CellSpacing = 0;
                                    htmltable1.CellPadding = 0;
                                    htmltable1.Border = 0;
                                    htmltable1.CellSpacing = 5; // Added by srivatsan for Transaction document header alignment
                                    htmltable1.Width = "250px";
                                    HtmlTableRow htmltablerow1 = new HtmlTableRow();
                                    HtmlTableCell htmltablecell1 = new HtmlTableCell();

                                    htmltablecell1 = htc;
                                    htmltablecell1.Align = "left";
                                    htmltablerow1.Controls.Add(htmltablecell1);

                                    htc = new HtmlTableCell();
                                    htc.Style.Add(HtmlTextWriterStyle.Left, "2px");
                                    htmltable1.Controls.Add(htmltablerow1);
                                    htc.Controls.Add(htmltable1);


                                    // }
                                }


                            }
                        }
                    }

                }
                else
                {
                    htc.Controls.Add(new LiteralControl("&nbsp;"));

                }


                //// added by srivatsan on May 25 for header alignment
                if (dsInput == null)
                {
                    if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("transdoc.aspx"))
                    {
                        //if (j == intRowCtrlCnt-1)
                        if (intRowCtrlCnt != 1)
                        {
                            if (strPageView == "1")
                            {
                                if (j == i + intRowCtrlCnt - 1)
                                {
                                    htc.Align = "Right";
                                    htc.Attributes.Add("class", "");
                                }
                            }
                        }
                    }
                }
                //

                htrObj.Cells.Add(htc);
            }

            #region MyRegion
            //htc = (HtmlTableCell)arlHtmlCells[i];
            //htrObj.Cells.Add(htc);

            //htc = new HtmlTableCell();
            //if ((i + 1) < arlHtmlCells.Count)
            //{
            //    htc = (HtmlTableCell)arlHtmlCells[i + 1];
            //}
            //else
            //{
            //    htc.Controls.Add(new LiteralControl(" "));
            //}
            //htrObj.Cells.Add(htc); 
            #endregion

            // Add, Remove Button will be added
            htc = new HtmlTableCell();
            if ((i + intRowCtrlCnt) >= arlHtmlCells.Count && blnMultiplePage)
            {
                #region MyRegion
                /*if (intCurrentRow == intTotalRow)
                {
                    Button btnAddObj = new Button();
                    btnAddObj.ID = "btn_" + strPageId + "_Add_1";
                    btnAddObj.Text = "Add";
                    btnAddObj.Click += new EventHandler(btnAddObj_Click);
                    btnAddObj.OnClientClick = "return AddRow('" + strPageId + "')";
                    htc.Controls.Add(btnAddObj);
                }
                else
                {*/

                #endregion
                // Remove button does not needed for first row
                if (intTotalRow > 1 && isViewMode() && Delete)
                {
                    if (dsInput != null) // Transaction Document page // Srivatsan trans doc default save
                    {

                        //Label lbl = new Label();
                        //lbl.Text = "<img src=\"Images/delete.GIF\"></img>";
                        ////lbl.ID = "btn_"+strPageId+"_Remove_"+intCurrentRow.ToString();
                        //lbl.ToolTip = "Remove";
                        //lbl.Attributes.Add("onclick", "javascript:updateclickstatus('del');  RemoveRow('" + strPageId + "','" + intCurrentRow.ToString() + "');");
                        //lbl.CssClass = "handCursor";
                        //htc.Controls.Add(lbl);


                        //LinkButton lnk = new LinkButton();
                        //lnk.Text = "Del";
                        //lnk.Style.Add("text-decoration", "none");
                        //lnk.Style.Add("border","none");
                        //lnk.Controls.Add(new LiteralControl("<img src=\"Images/delete.GIF\" style=\"border:none;\"></img>"));
                        //htc.Controls.Add(lnk);

                        LinkButton btnlnkRemove = new LinkButton();
                        btnlnkRemove.ID = "btn_" + strPageId + "_Remove_" + intCurrentRow.ToString();
                        btnlnkRemove.CausesValidation = false;
                        btnlnkRemove.ToolTip = "Remove";
                        btnlnkRemove.Style.Add("text-decoration", "none");
                        btnlnkRemove.Style.Add("border", "none");
                        btnlnkRemove.Text = "<img id=\"imgDel_" + strPageId + "_Remove_" + intCurrentRow.ToString() + "\" src=\"Images/delete.GIF\" style=\"border:none;\"></img>";
                        string imgid = "imgDel_" + strPageId + "_Remove_" + intCurrentRow.ToString();
                        //btnlnkRemove.OnClientClick = "javascript:updateclickstatus('del');  RemoveRow('" + strPageId + "','" + intCurrentRow.ToString() + "');";
                        btnlnkRemove.OnClientClick = "javascript:if(document.getElementById('" + imgid + "')!=null){document.getElementById('" + imgid + "').src='Images/load.GIF';} updateclickstatus('del');  RemoveRow('" + strPageId + "','" + intCurrentRow.ToString() + "');";
                        //btnlnkRemove.OnClientClick = "javascript:if(document.getElementById('ctl00_ContentPlaceHolder3_" + btnlnkRemove.ID + "')!=null) {document.getElementById('ctl00_ContentPlaceHolder3_" + btnlnkRemove.ID + "').innerHTML = \"<img src=\"Images/load.GIF\" style=\"border:none;\"></img>\"; alert('set');} alert('ok');updateclickstatus('del');  RemoveRow('" + strPageId + "','" + intCurrentRow.ToString() + "');";

                        btnlnkRemove.Click += new EventHandler(btnlnkRemove_Click);
                        htc.Controls.Add(btnlnkRemove);


                        //ImageButton btnRemoveObj = new ImageButton();
                        //btnRemoveObj.ID = "btn_" + strPageId + "_Remove_" + intCurrentRow.ToString();
                        //btnRemoveObj.CausesValidation = false;
                        //btnRemoveObj.AlternateText = "Remove";
                        //btnRemoveObj.ToolTip = "Remove";
                        //btnRemoveObj.ImageUrl = "Images/delete.GIF";
                        //btnRemoveObj.Click += new ImageClickEventHandler(btnRemoveimgObj_Click);
                        //btnRemoveObj.OnClientClick = "updateclickstatus('del');  RemoveRow('" + strPageId + "','" + intCurrentRow.ToString() + "');";
                        //btnRemoveObj.Visible = false;
                        //htc.Controls.Add(btnRemoveObj);
                    }
                    else
                    {
                        Button btnRemoveObj = new Button();
                        btnRemoveObj.ID = "btn_" + strPageId + "_Remove_" + intCurrentRow.ToString();
                        btnRemoveObj.Text = "Remove";
                        btnRemoveObj.Click += new EventHandler(btnRemoveObj_Click);
                        btnRemoveObj.OnClientClick = "javascript:RemoveRow('" + strPageId + "','" + intCurrentRow.ToString() + "');";
                        //btnRemoveObj.OnClientClick = "javascript:RemoveRow('" + strPageId + "','" + intCurrentRow.ToString() + "'); __doPostBack('" + btnRemoveObj.ID + "','');";
                        btnRemoveObj.UseSubmitBehavior = false;
                        htc.Controls.Add(btnRemoveObj);
                    }
                }
                else
                {
                    htc.Controls.Add(new LiteralControl("&nbsp;"));

                }
                //}
            }
            else
            {
                htc.Controls.Add(new LiteralControl("&nbsp;"));

            }

            htrObj.Cells.Add(htc);
            htrObj.VAlign = "middle";
            if (dsInput != null) // Transaction document page
            {
                htrObj.Attributes.Add("class", "Dynamic_TransDocHtmlTableCell"); // Modified by srivatsan on May 10 2009
            }
            else
            {
                //if (IsTransactionDocumentPage())
                //{
                //  htrObj.Attributes.Add("class", "Dynamic_TransDocHtmlTableCell");
                //}
                //else
                //{
                htrObj.Attributes.Add("class", "Dynamic_HtmlTableCell");
                //}
            }
            htaPageTable.Rows.Add(htrObj);
            //htaPageTable.Border = 1;
            //htaPageTable.Style.Add("empty-cells","hide");

        }

        return blnStatus;
    }

    private bool checkandAppendSectionHeader(ref HtmlTable htaPageTable, int colspan, string intCurrentRow, HtmlTableCell ccell , ref string strSectionName) //added By Dhanapal December 07 2010 For Section
    {
        try
        {
            if (ccell.Controls[0] is LiteralControl)
            {
                string strSectionNameWithId = ccell.InnerText;

                if (strSectionNameWithId.StartsWith("pe_sectionheader_")) //To Confirm the Section Name
                {
                    strSectionName = strSectionNameWithId; // The Section Name Assigned Here
                    if (checkForEmptySection(strSectionNameWithId))
                    {
                        appendSectionHeader(ref  htaPageTable, colspan, strSectionNameWithId, intCurrentRow.ToString());
                        return true;
                    }
                    else
                    {
                        return true;
                    }
                }
            }
            return false;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in checkandAppendSectionHeader function. Error " + e.Message);
            return false;
        }

    }

    private bool checkForEmptySection(string strSectionNameWithId)//Added By Dhanapal on Dec 09 2010 For Checking Empty Section Name and Sys Var Row
    {
        if (strSectionNameWithId.Trim() == "pe_sectionheader___MB_EMPTY_SECTION" || strSectionNameWithId.Trim() == "pe_sectionheader___SYS_VAR__" ) 
            return false;
        else
            return true;
    }

    private void appendSectionHeader(ref HtmlTable htaPageTable, int colspan, string sectionnamewithid, string intCurrentRow) //added By Dhanapal November 25 2010 For Section
    {
        CommonFunctions comm = new CommonFunctions();
        string strSectionName = "";
        string strMatchStr = "pe_sectionheader_";
        string strSectionRowId = "";
        strSectionName = sectionnamewithid.Substring(strMatchStr.Length, sectionnamewithid.Length - strMatchStr.Length);
        HtmlTableRow htr = new HtmlTableRow();


        HtmlTableCell htclinitial = new HtmlTableCell();
        htclinitial.Controls.Add(new LiteralControl("&nbsp;")); //prefix empty cell
        htr.Cells.Add(htclinitial);
        //htr.Controls.Add(htclinitial);

        HtmlTableCell htcl = new HtmlTableCell();
        htcl.ColSpan = colspan;
        //htcl.InnerHtml = "<b>" + strSectionName + "</b>";
        strSectionRowId = sectionnamewithid + "_" + intCurrentRow;

        //htcl.Attributes.Add("class", "Dynamic_PageHeaderRow");
        htcl.Attributes.Add("class", "Dynamic_PageSectionHeaderRow");

        Panel pnlleft = new Panel();
        pnlleft.Attributes.Add("class", "Dynamic_PageSectionHeaderName");
        pnlleft.Controls.Add(new LiteralControl(strSectionName));
        htcl.Controls.Add(pnlleft);

        Panel pnlright = new Panel();
        pnlright.Attributes.Add("class", "Dynamic_PageSectionHeaderIconHolder");
        /***Changes Done By Dhanapal On Dec 09 2010***********/
       
        /************************************************/
        //ImageButton imgbtn = new ImageButton();
        //imgbtn.ImageUrl = "Images/collapse3.GIF";
        //imgbtn.ToolTip = "Click Here";
        //imgbtn.ID = "ExpandCollapseImage" + strSectionRowId;
        string strimgbtnid = "ExpandCollapseImage" + strSectionRowId;
        LiteralControl lcimgbtn = new LiteralControl();
        //lcimgbtn.Text = "<img src='Images/collapse3.GIF' id='" + strimgbtnid + "' onclick=\"ExpandandCollapseSection(this ,'"  + strSectionRowId +   "')\";>";

        lcimgbtn.Text = "<img src='Images/collapse3.GIF' title='Collapse' id='" + strimgbtnid + "'>";

        //lcimgbtn.Text = "<input type='image' src='Images/collapse3.GIF' id='" + strimgbtnid + "' onclick=\"ExpandandCollapseSection(this ,'" + strSectionRowId + "')\";>";
       
        //imgbtn.OnClientClick = "javascript:ExpandandCollapseSection(this " + ",'" + strSectionRowId + "');return false;"; //Commented by Dhanapal TO stop btnEvent
        //String strClientbtncode = "<input type=\"image\" src=\"Images/collapse3.GIF\">";
        //LiteralControl lcimg = new LiteralControl(strClientbtncode);
        pnlright.Controls.Add(lcimgbtn);
        htcl.Controls.Add(pnlright);

        htr.Cells.Add(htcl);
        //htr.Controls.Add(htcl);

        HtmlTableCell htclend = new HtmlTableCell();
        htclend.Controls.Add(new LiteralControl("&nbsp;"));  //End empty cell
        htr.Cells.Add(htclend);
        
        //htr.Attributes.Add("onclick", "javascript:ExpandandCollapseSection(document.getElementById('ctl00_ContentPlaceHolder3_" + strimgbtnid + "'),'" + strSectionRowId + "');return false;");
        htr.Attributes.Add("onclick", "javascript:ExpandandCollapseSection(document.getElementById('" + strimgbtnid + "'),'" + strSectionRowId + "');");

        //htr.Attributes.Add("onclick", "document.getElementById('" + strimgbtnid + "').click();");
        //htr.Controls.Add(htclend);
        htr.ID = comm.RemoveSpecialCharacters(strSectionRowId); // Modified by 'Imran Gani' on 24-Jun-2013, to handle special characters
        htaPageTable.Controls.Add(htr);
    }

    void btnlnkRemove_Click(object sender, EventArgs e)
    {
        LinkButton btnObj = (LinkButton)sender;
        RemovePageRow RPR = new RemovePageRow();
        //RPR.RemoveRow(frmMainObj, dsePageInfoMain);
        RPR.RemoveRow(btnObj.Page.Form, dsePageInfoMain);
        updateTotalAmountOnEvents();

    }

    private void AssignTotalFieldEvents(ref HtmlTableCell htc, DataRow[] drtotals, string strPageId)
    {
        // Added by srivatsan on May 12 for events
        if (drtotals != null)
        {
            if (htc.Controls.Count > 0)
            {
                foreach (Control cn in htc.Controls)
                {
                    if (drtotals.Length > 0)
                    {
                        for (int k = 0; k < drtotals.Length; k++)
                        {
                            if (cn != null)
                            {
                                if (cn.ID != null)
                                {
                                    if (drtotals[k]["attrib_id"].ToString() != "")
                                    {
                                        if (cn.ID.ToLower().Contains(drtotals[k]["attrib_id"].ToString().ToLower()))
                                        {
                                            if (cn is TextBox)
                                            {
                                                TextBox textbox1 = (TextBox)cn;
                                                //textbox1.CausesValidation = false;
                                                //textbox1.Attributes.Add("onChange", "javascript:seteventsender('"+textbox1.ID+"');");
                                                //textbox1.AutoPostBack = true;
                                                //textbox1.TextChanged += new EventHandler(textbox1_TextChanged);
                                                //textbox1.Attributes.Add("onchange", "javascript:transdoc_calculateTotal('" + textbox1.ID.Replace("_" + drcontrolevents[k]["source_control"].ToString(), "") + "','" + drcontrolevents[k]["source_control"].ToString() + "','','" + drcontrolevents[k]["target_control"].ToString() + "');");

                                                // Working event commented for using appending attributes
                                                //textbox1.Attributes.Add("onchange", "javascript:transdoc_calculateTotal('" + strPageId + "','" + drtotals[k]["attrib_id"].ToString() + "','','" + "total_" + strPageId + "_" + drtotals[k]["attrib_id"].ToString() + "');");

                                                setAttribute(textbox1.Attributes, "onchange", "javascript:transdoc_calculateTotal('" + strPageId + "','" + drtotals[k]["attrib_id"].ToString() + "','','" + "total_" + strPageId + "_" + drtotals[k]["attrib_id"].ToString() + "');");
                                            }
                                            if (cn is DropDownList)
                                            {
                                                DropDownList dropdown1 = (DropDownList)cn;
                                                dropdown1.CausesValidation = false;
                                                // Working event commented for using appending attributes
                                                //dropdown1.Attributes.Add("onChange", "javascript:seteventsender('" + dropdown1.ID + "');");
                                                setAttribute(dropdown1.Attributes, "onchange", "javascript:seteventsender('" + dropdown1.ID + "');");
                                                dropdown1.AutoPostBack = true;
                                                dropdown1.SelectedIndexChanged += new EventHandler(dropdown1_SelectedIndexChanged);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

    }

    void btnRemoveimgObj_Click(object sender, EventArgs e)
    {
        //Button btnObj = (Button)sender;
        ImageButton btnObj = (ImageButton)sender;
        //btnObj.Parent.FindControl("tblDynamicMain");
        RemovePageRow RPR = new RemovePageRow();
        RPR.RemoveRow(frmMainObj, dsePageInfoMain);

        updateTotalAmountOnEvents();
    }

    private void updateTotalAmountOnEvents()
    {
        //if (frmMainObj.FindControl("ctl00$ContentPlaceHolder3$UpdatePanel1") != null)
        //{
        //    UpdatePanel panel = (UpdatePanel)frmMainObj.FindControl("ctl00$ContentPlaceHolder3$UpdatePanel1");
        //    panel.Update();
        //}
        return;
        string page_id = dsePageInfoMain.Tables["Page"].Rows[0]["page_id"].ToString();
        string tablename = "tbl_" + page_id;

        HtmlTable htaPageTable = (HtmlTable)FindControl(frmMainObj.Controls, tablename);
        DataRow[] droPageCtrl = dsePageInfoMain.Tables["PageCtrl"].Select();
        DataRow[] drTotals = getTotalFields(dsePageInfoMain.Tables["Page"].Rows[0]["af_row_id"].ToString());
        DataTable dtaPage = dsePageInfoMain.Tables["Page"].Copy();

        //HtmlInputHidden hihObj = (HtmlInputHidden)frmMainObj.FindControl("ctl00$_sys" + page_id + "_RowCount");
        //int intRowCnt = Convert.ToInt32(hihObj.Value);
        int intRowCnt = Convert.ToInt32(HttpContext.Current.Session["hfrowcount"].ToString());
        // AddTotalFields(htaPageTable, droPageCtrl, drTotals, dtaPage, intRowCnt, frmMainObj, htaPageTable);




        TransactionDocument TD = new TransactionDocument();
        TD.updateTotalFields(frmMainObj, drTotals, dsePageInfoMain, intRowCnt);
    }

    //private bool GeneratePageTable(ArrayList arlHtmlCells, HtmlTable htaPageTable, DataRow droPage, int intCurrentRow, int intTotalRow, int intStartFrom, bool Delete, DataSet dsControlEvents)
    //{
    //    bool blnStatus = true;
    //    bool blnMultiplePage = Convert.ToBoolean(droPage["multiple_recs_page"].ToString());
    //    string strPageId = droPage["page_id"].ToString();
    //    string strPageView = "";

    //    DataRow[] drcontrolevents = null;

    //    if (dsControlEvents != null)   // Added by srivatsan for control events
    //    {
    //        if (dsControlEvents.Tables.Count > 0)
    //        {
    //            if (dsControlEvents.Tables.Contains("ControlEvents"))//ssks
    //            {
    //                if (dsControlEvents.Tables["ControlEvents"].Rows.Count > 0)
    //                {
    //                    drcontrolevents = dsControlEvents.Tables["ControlEvents"].Select();
    //                }
    //            }
    //        }
    //    }//


    //    if (droPage["page_view"] == DBNull.Value)
    //    {
    //        strPageView = GlobalValues.DefaultPageView;
    //    }
    //    else
    //    {
    //        strPageView = droPage["page_view"].ToString();
    //    }
    //    int intRowCtrlCnt = 0;
    //    if (droPage["control_per_row"] == DBNull.Value)
    //    {
    //        intRowCtrlCnt = GlobalValues.DefaultControlPerRow;
    //    }
    //    else
    //    {
    //        intRowCtrlCnt = Convert.ToInt32(droPage["control_per_row"].ToString());
    //    }

    //    if (strPageView == "2")
    //    {
    //        intRowCtrlCnt = intRowCtrlCnt * 2;
    //    }

    //    if (intStartFrom > 0 && intCurrentRow == 2 && isViewMode() && Delete)
    //    {
    //        Button btnRemoveObj = new Button();
    //        btnRemoveObj.ID = "btn_" + strPageId + "_Remove_1";
    //        btnRemoveObj.Text = "Remove";
    //        btnRemoveObj.Click += new EventHandler(btnRemoveObj_Click);
    //        btnRemoveObj.OnClientClick = "return RemoveRow('" + strPageId + "','1')";//btnRemoveObj.OnClientClick = "return RemoveRow('" + strPageId + "','1" + intCurrentRow.ToString() + "')";
    //        //if (strPageView == "1")
    //        //{
    //        htaPageTable.Rows[htaPageTable.Rows.Count - 1].Cells[intRowCtrlCnt + 1].Controls.Clear();
    //        htaPageTable.Rows[htaPageTable.Rows.Count - 1].Cells[intRowCtrlCnt + 1].Controls.Add(btnRemoveObj);
    //        /*}
    //        if (strPageView == "2")
    //        {
    //            htaPageTable.Rows[htaPageTable.Rows.Count - 1].Cells[(intRowCtrlCnt*2) + 1].Controls.Clear();
    //            htaPageTable.Rows[htaPageTable.Rows.Count - 1].Cells[(intRowCtrlCnt * 2) + 1].Controls.Add(btnRemoveObj);
    //        }*/
    //    }
    //    for (int i = 0; i < arlHtmlCells.Count; i = i + intRowCtrlCnt)
    //    {
    //        HtmlTableRow htrObj = new HtmlTableRow();
    //        HtmlTableCell htc = new HtmlTableCell();
    //        if (blnMultiplePage && i == 0)
    //        {
    //            htc.Controls.Add(new LiteralControl(intCurrentRow.ToString()));
    //        }
    //        else
    //        {
    //            htc.Controls.Add(new LiteralControl(" "));
    //        }
    //        htrObj.Cells.Add(htc);

    //        for (int j = i; j < i + intRowCtrlCnt; j++)
    //        {
    //            htc = new HtmlTableCell();
    //            if (j < arlHtmlCells.Count)
    //            {
    //                htc = (HtmlTableCell)arlHtmlCells[j];

    //                SetEventsforControl(ref htc, drcontrolevents);  // Added by srivatsan for control events
    //                if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("transdoc.aspx"))
    //                {
    //                    if (htc.Controls.Count > 0)  // Added by srivatsan for Header right alignments
    //                    {

    //                        int cntrlcount = htc.Controls.Count;
    //                        if (strPageView == "1")
    //                        {
    //                            // for (int k = 0; k < cntrlcount; k++)
    //                            //{
    //                            HtmlTable htmltable1 = new HtmlTable();
    //                            htmltable1.CellSpacing = 0;
    //                            htmltable1.CellPadding = 0;
    //                            htmltable1.Border = 0;
    //                            htmltable1.Width = "250px";
    //                            HtmlTableRow htmltablerow1 = new HtmlTableRow();
    //                            HtmlTableCell htmltablecell1 = new HtmlTableCell();

    //                            htmltablecell1 = htc;
    //                            htmltablecell1.Align = "left";

    //                            htmltablerow1.Controls.Add(htmltablecell1);

    //                            htc = new HtmlTableCell();

    //                            htmltable1.Controls.Add(htmltablerow1);

    //                            htc.Controls.Add(htmltable1);


    //                            // }
    //                        }


    //                    }
    //                }

    //            }
    //            else
    //            {
    //                htc.Controls.Add(new LiteralControl(" "));
    //            }


    //            //// added by srivatsan on May 25 for header alignment
    //            if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("transdoc.aspx"))
    //            {
    //                //if (j == intRowCtrlCnt-1)
    //                if (intRowCtrlCnt != 1)
    //                {
    //                    if (strPageView == "1")
    //                    {
    //                        if (j == i + intRowCtrlCnt - 1)
    //                        {
    //                            htc.Align = "Right";
    //                            htc.Attributes.Add("class", "");
    //                        }
    //                    }
    //                }
    //            }
    //                //

    //            htrObj.Cells.Add(htc);
    //        }

    //        #region MyRegion
    //        //htc = (HtmlTableCell)arlHtmlCells[i];
    //        //htrObj.Cells.Add(htc);

    //        //htc = new HtmlTableCell();
    //        //if ((i + 1) < arlHtmlCells.Count)
    //        //{
    //        //    htc = (HtmlTableCell)arlHtmlCells[i + 1];
    //        //}
    //        //else
    //        //{
    //        //    htc.Controls.Add(new LiteralControl(" "));
    //        //}
    //        //htrObj.Cells.Add(htc); 
    //        #endregion

    //        // Add, Remove Button will be added
    //        htc = new HtmlTableCell();
    //        if ((i + intRowCtrlCnt) >= arlHtmlCells.Count && blnMultiplePage)
    //        {
    //            #region MyRegion
    //            /*if (intCurrentRow == intTotalRow)
    //            {
    //                Button btnAddObj = new Button();
    //                btnAddObj.ID = "btn_" + strPageId + "_Add_1";
    //                btnAddObj.Text = "Add";
    //                btnAddObj.Click += new EventHandler(btnAddObj_Click);
    //                btnAddObj.OnClientClick = "return AddRow('" + strPageId + "')";
    //                htc.Controls.Add(btnAddObj);
    //            }
    //            else
    //            {*/

    //            #endregion
    //            // Remove button does not needed for first row
    //            if (intTotalRow > 1 && isViewMode() && Delete)
    //            {
    //                Button btnRemoveObj = new Button();
    //                btnRemoveObj.ID = "btn_" + strPageId + "_Remove_" + intCurrentRow.ToString();
    //                btnRemoveObj.Text = "Remove";
    //                btnRemoveObj.Click += new EventHandler(btnRemoveObj_Click);
    //                btnRemoveObj.OnClientClick = "return RemoveRow('" + strPageId + "','" + intCurrentRow.ToString() + "')";
    //                htc.Controls.Add(btnRemoveObj);
    //            }
    //            else
    //            {
    //                htc.Controls.Add(new LiteralControl("&nbsp;"));
    //            }
    //            //}
    //        }
    //        else
    //        {
    //            htc.Controls.Add(new LiteralControl("&nbsp;"));
    //        }

    //        htrObj.Cells.Add(htc);
    //        htrObj.VAlign="middle";
    //        htrObj.Attributes.Add("class", "Dynamic_HtmlTableCell");
    //        htaPageTable.Rows.Add(htrObj);
    //    }
    //    return blnStatus;
    //}

    private void AddDeleteButtonForTransDocPage(ref HtmlTable htaPageTable, string strPageId, int intRowCtrlCnt)
    {
        try
        {
            ImageButton btnRemoveObj = new ImageButton();
            btnRemoveObj.CausesValidation = false;
            btnRemoveObj.ID = "btn_" + strPageId + "_Remove_1";
            btnRemoveObj.ImageUrl = "Images/delete.GIF";
            btnRemoveObj.ToolTip = "Delete";
            btnRemoveObj.Click += new ImageClickEventHandler(btnRemoveObj_Click);
            btnRemoveObj.OnClientClick = "updateclickstatus('del'); return RemoveRow('" + strPageId + "','1')";//btnRemoveObj.OnClientClick = "return RemoveRow('" + strPageId + "','1" + intCurrentRow.ToString() + "')";
            htaPageTable.Rows[htaPageTable.Rows.Count - 1].Cells[intRowCtrlCnt + 1].Controls.Clear();
            htaPageTable.Rows[htaPageTable.Rows.Count - 1].Cells[intRowCtrlCnt + 1].Controls.Add(btnRemoveObj);
        }
        catch
        {
        }
    }

    void cb1_CheckedChanged(object sender, EventArgs e)  // control events
    {
        PageControlEvents PCE = new PageControlEvents();
        PCE.DoControlEvents(frmMainObj, dsePageInfoMain);
    }

    void textbox1_TextChanged(object sender, EventArgs e) //control events
    {
        PageControlEvents PCE = new PageControlEvents();
        PCE.DoControlEvents(frmMainObj, dsePageInfoMain);
    }

    void dropdown1_SelectedIndexChanged(object sender, EventArgs e) // control events
    {
        PageControlEvents PCE = new PageControlEvents();
        PCE.DoControlEvents(frmMainObj, dsePageInfoMain);
    }

    // This function will create events for the controls if it has Control events
    private void SetEventsforControl(ref HtmlTableCell htc, DataRow[] drcontrolevents, string strPageId)
    {

        if (htc.Controls.Count > 0)
        {
            foreach (Control cn in htc.Controls)
            {
                if (drcontrolevents != null)
                {
                    if (drcontrolevents.Length > 0)
                    {
                        for (int k = 0; k < drcontrolevents.Length; k++)
                        {
                            if (cn != null)
                            {
                                if (cn.ID != null)
                                {
                                    if (cn.ID.ToLower().Contains(drcontrolevents[k]["source_control"].ToString().ToLower()))
                                    {
                                        if (cn is TextBox)
                                        {
                                            TextBox textbox1 = (TextBox)cn;
                                            //textbox1.AutoPostBack = true;
                                            //textbox1.EnableViewState = true;
                                            //textbox1.TextChanged += new EventHandler(textbox1_TextChanged);                                            
                                            setAttribute(textbox1.Attributes, "onblur", "javascript:contrlevnt_handleEvent('" + strPageId + "','" + drcontrolevents[k]["target_control"].ToString() + "',\"" + drcontrolevents[k]["expression"].ToString().Trim() + "\",'" + drcontrolevents[k]["event_type"].ToString() + "','" + textbox1.ID.Replace(strPageId + "_" + drcontrolevents[k]["source_control"].ToString(), "").TrimStart('_') + "',this,'" + drcontrolevents[k]["target_trigger_values"].ToString() + "');");
                                        }
                                        if (cn is DropDownList)
                                        {
                                            DropDownList dropdown1 = (DropDownList)cn;
                                            //dropdown1.AutoPostBack = true;
                                            //dropdown1.SelectedIndexChanged += new EventHandler(dropdown1_SelectedIndexChanged);
                                            setAttribute(dropdown1.Attributes, "onchange", "javascript:contrlevnt_handleEvent('" + strPageId + "','" + drcontrolevents[k]["target_control"].ToString() + "',\"" + drcontrolevents[k]["expression"].ToString().Trim() + "\",'" + drcontrolevents[k]["event_type"].ToString() + "','" + dropdown1.ID.Replace(strPageId + "_" + drcontrolevents[k]["source_control"].ToString(), "").TrimStart('_') + "',this,'" + drcontrolevents[k]["target_trigger_values"].ToString() + "');");
                                        }
                                        if (cn is CheckBox)
                                        {
                                            CheckBox cb1 = (CheckBox)cn;
                                            //cb1.AutoPostBack = true;
                                            //cb1.CheckedChanged += new EventHandler(cb1_CheckedChanged);                                            
                                            setAttribute(cb1.Attributes, "onclick", "javascript:contrlevnt_handleEvent('" + strPageId + "','" + drcontrolevents[k]["target_control"].ToString() + "',\"" + drcontrolevents[k]["expression"].ToString().Trim() + "\",'" + drcontrolevents[k]["event_type"].ToString() + "','" + cb1.ID.Replace(strPageId + "_" + drcontrolevents[k]["source_control"].ToString(), "").TrimStart('_') + "',this,'" + drcontrolevents[k]["target_trigger_values"].ToString() + "');");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

    }



    void btnRemoveObj_Click(object sender, EventArgs e)
    {
        Button btnObj = (Button)sender;
        //btnObj.Parent.FindControl("tblDynamicMain");
        RemovePageRow RPR = new RemovePageRow();
        RPR.RemoveRow(frmMainObj, dsePageInfoMain);

        //throw new Exception("The method or operation is not implemented.");
    }

    void btnAddObj_Click(object sender, EventArgs e)
    {
        //throw new Exception("The method or operation is not implemented.");
    }
    private bool PageTooltipAdd(HtmlTable htaMain, DataRow droPage)//, string strMenuRowId, security objSec)
    {
        try
        {
            if (!droPage.Table.Columns.Contains("page_desc")) return false;
            if (droPage["page_desc"].ToString().Trim() == "") return false;
            HtmlTableRow htr = new HtmlTableRow();
            HtmlTableCell htc = new HtmlTableCell();
            htc.Controls.Add(new LiteralControl(getTooltipContent(droPage)));
            htr.Controls.Add(htc);
            htaMain.Rows.Add(htr);
            return true;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in PageTooltipAdd function. Error " + e.Message);
            return false;
        }
    }
    private string getTooltipContent(DataRow droPage)
    {
        if (!droPage.Table.Columns.Contains("page_desc")) return "";
        if (droPage["page_desc"].ToString().Trim() == "") return "";
        //string ret = "";
        //ret = "<div id=\"page_tooltip_div\" style=\"border-bottom:solid 1px #000000;\">";
        //ret += "<table border=\"0\" cellpadding=\"5\" cellspacing=\"0\" width=\"100%\"><tr><td width=\"10%\" valign=\"center\" align=\"center\"><img src=\"Images/info.gif\" border=\"0\"></img></td><td width=\"80%\" class=\"controlFont\">";
        //ret += droPage["page_desc"].ToString();
        //ret += "</td></tr></table>";
        //ret +="</div>";
        return getContent(HttpContext.Current.Server.MapPath("") + @"\scripts\pagetooltipcontent.txt").Replace("<<content>>", CommonFunctions.SafeEncode(droPage["page_desc"].ToString()));
    }
    private string getContent(string fileName)//created by sanal on 12 Dec 2007
    {
        try
        {
            if (!System.IO.File.Exists(fileName)) return "";
            string temp = "";
            System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
            temp = sr.ReadToEnd();
            sr.Close(); sr = null;
            return temp;
        }
        catch (Exception e)
        {
            return "";
        }
    }
    private string getTootipIcon(DataRow droPage)
    {
        try
        {
            if (!droPage.Table.Columns.Contains("page_desc")) return "";
            if (droPage["page_desc"].ToString().Trim() == "") return "";
            return "&nbsp;<img id=\"page_tooltip_img\" style=\"cursor:pointer;\" src=\"Images/collapse3.gif\" onClick=\"javascript:showHideTooltipDIV();\" border=\"0\"></img>";
        }
        catch (Exception e)
        {
            return "";
        }
    }
    private bool PageHeaderAdd(HtmlTable htaMain, DataRow droPage, string strMenuRowId, security objSec, DataSet dsinput)
    {
        bool blnStatus = true;
        HtmlTableRow htrObj = new HtmlTableRow();
        htrObj.Attributes.Add("class", "Dynamic_PageHeaderRow");

        HtmlTableCell htcPageCell = new HtmlTableCell();//03-Oct-2007
        HtmlTable htPageHeader = new HtmlTable();//03-Oct-2007
        //htPageHeader.Border = 1;
        /* Lines commanded by 'Imran Gani' on 22-Nov-12, to set the width as 100%.
        if (HttpContext.Current.Request.QueryString["VMODE"] != null)
        {
            if (HttpContext.Current.Request.QueryString["VMODE"] == "1")
            {
                if (manageADS()) htPageHeader.Width = "181%";
                else htPageHeader.Width = "187%";
            }
        }
        else
        { htPageHeader.Width = "100%"; }
        */
        htPageHeader.Width = "100%";
        HtmlTableRow htrPageHeader = new HtmlTableRow();//03-Oct-2007
        int intRowCtrlCnt = -1;
        if (droPage["control_per_row"] == DBNull.Value)
            intRowCtrlCnt = GlobalValues.DefaultControlPerRow;
        else
            intRowCtrlCnt = Convert.ToInt32(droPage["control_per_row"].ToString());

        HtmlTableCell htcObj = new HtmlTableCell();
        string strPageView = "";
        if (droPage["page_view"] == DBNull.Value)
            strPageView = GlobalValues.DefaultPageView;
        else
            strPageView = droPage["page_view"].ToString();

        if (strPageView == "1")
            htcObj.ColSpan = intRowCtrlCnt + 1;
        else if (strPageView == "2")
            htcObj.ColSpan = (intRowCtrlCnt * 2) + 1;

        string strPagesetRowId = "";
        string strHeaderText = droPage["page_name"].ToString();


        strHeaderText = GetPageIcons(droPage["page_id"].ToString()).Text + strHeaderText; // Added by srivatsan


        if (HttpContext.Current.Request.QueryString["PK"] == null)
            strHeaderText = strHeaderText + " - Add";
        else
        {
            if (HttpContext.Current.Request.QueryString["CPY"] != null)
                strHeaderText = strHeaderText + " - Copy";
            else if (HttpContext.Current.Request.QueryString["VMODE"] != null)
                strHeaderText = strHeaderText + " - View";
            else
                strHeaderText = strHeaderText + " - Edit";
        }

        strHeaderText += getTootipIcon(droPage);

        if (frmMainObj.Page.Request.QueryString["pgs_id"] != null)
            strPagesetRowId = frmMainObj.Page.Request.QueryString["pgs_id"].ToString();

        htcObj.Controls.Add(new LiteralControl(strHeaderText));
        //if (HttpContext.Current.Request.QueryString["PK"] != null)
        //    htcObj.Width = "42%";//03-Oct-2007
        //else
        //    htcObj.Width = "36%";
        htcObj.Width = "30%"; // modified by srivatsan (34% to 29%)
        htrPageHeader.Cells.Add(htcObj);//htrObj.Cells.Add(htcObj);

        htcObj = new HtmlTableCell();
        bool blnMultiplePage = false;
        string strPageId = droPage["page_id"].ToString();
        blnMultiplePage = Convert.ToBoolean(droPage["multiple_recs_page"].ToString());
        Button btnAddObj = null;
        //ImageButton btnimgAddObj = null;
        LinkButton btnimgAddObj = null;
        //Label btnimgAddObj = null;
        if (dsinput != null)
        {


            if (blnMultiplePage)
            {
                //btnimgAddObj = new Label();
                //btnimgAddObj.Text = "<img src=\"Images/add.GIF\"></img> Add";
                //btnimgAddObj.Attributes.Add("onclick", "javascript:updateclickstatus('add'); return AddRow('" + strPageId + "');");
                //btnimgAddObj.CssClass = "handCursor";
                btnimgAddObj = new LinkButton();
                btnimgAddObj.ID = "btn_" + strPageId + "_Transdoc_Add_1";
                btnimgAddObj.CssClass = "Lnkbttn";
                btnimgAddObj.Text = "<img id=\"imgAdd_" + strPageId + "_Transdoc_Add_1\" src=\"Images/add.GIF\" style=\"border:none;\"></img> Add";
                btnimgAddObj.ToolTip = "Add";
                btnimgAddObj.CausesValidation = false;
                btnimgAddObj.Style.Add("text-decoration", "none");
                btnimgAddObj.Style.Add("border", "none");
                //btnimgAddObj.Attributes.Add("onclick", "javascript:if(document.getElementById('ctl00_ContentPlaceHolder3_" + btnimgAddObj.ID + "')!=null) {alert('add');document.getElementById('ctl00_ContentPlaceHolder3_" + btnimgAddObj.ID + "').innerHTML=document.getElementById('ctl00_ContentPlaceHolder3_" + btnimgAddObj.ID + "').innerHTML.replace('add.GIF','load.GIF');}  updateclickstatus('add'); return AddRow('" + strPageId + "')");
                //working
                //btnimgAddObj.Attributes.Add("onclick", "javascript:if(document.getElementById('imgAdd_"+strPageId+"_Transdoc_Add_1')!=null) {document.getElementById('imgAdd_"+strPageId+"_Transdoc_Add_1').src = 'images/load.gif';}  updateclickstatus('add'); return AddRow('" + strPageId + "')");
                btnimgAddObj.Attributes.Add("onclick", "javascript:if(document.getElementById('imgAdd_" + strPageId + "_Transdoc_Add_1')!=null) {document.getElementById('imgAdd_" + strPageId + "_Transdoc_Add_1').src = 'images/load.gif'; document.getElementById('ctl00_ContentPlaceHolder3_btn_" + strPageId + "_Transdoc_Add_1').disabled=true;}  updateclickstatus('add'); return AddRow('" + strPageId + "')");
                btnimgAddObj.Click += new EventHandler(btnimgAddObj_Click);
                ////btnimgAddObj = new ImageButton();//Button btnAddObj = new Button();
                ////btnimgAddObj.ID = "btn_" + strPageId + "_Add_1";
                ////btnimgAddObj.AlternateText = "Add";
                ////btnimgAddObj.ToolTip = "Add";
                ////btnimgAddObj.ImageUrl = "Images/add.GIF";
                ////btnimgAddObj.Click += new ImageClickEventHandler(btnAddObj_Click);   //uncommented by srivatsan on May 21 2009
                ////btnimgAddObj.OnClientClick = "updateclickstatus('add'); return AddRow('" + strPageId + "')";
            }
        }

        if (htaMain.Rows.Count < 1)//changed by Prithi on 14-nov-2008
        {
            //Label lblObj = new Label();
            ////strHeaderText = @"<a href=""DisplayGrid.aspx?pgs_id=" + strPagesetRowId + "&mn=" + strMenuRowId + @"""><font color=""black""><b>List</b></font></a>";
            //strHeaderText = @"<a href=""#"" onClick=""javascript:history.back();return false;""><font color=""black""><b>&lt;&lt;&nbsp;Back</b></font></a>";
            //lblObj.Text = strHeaderText;
            ////lblObj.Width = 100;
            //htcObj.Controls.Add(lblObj);
            Literal l = new Literal();
            l.Text = "&nbsp;";
            htcObj.Controls.Add(l);
            htcObj.ID = blnMultiplePage ? "addNoButtons" : "addButtons";
            htcObj.Width = "37%"; // modified by srivatsan (33% to 38%)
            htcObj.Align = "Right";
            htcObj.NoWrap = true;

            if (dsinput != null)
            {
                if (blnMultiplePage)
                {
                    if (HttpContext.Current.Request.QueryString["VMODE"] == null)
                    {
                        htcObj.Align = "Left";
                        htcObj.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
                        htcObj.Controls.Add(btnimgAddObj);
                        //htcObj.Controls.Add(lblimgAddObj);
                        //htcObj.Controls.Add(new LiteralControl("&nbsp;Add"));

                    }
                }
            }
            //getHeaderButtons(ref htcObj);
        }
        //added for view mode
        if (HttpContext.Current.Request.QueryString["VMODE"] != null)
            if (HttpContext.Current.Request.QueryString["VMODE"] == "1")
                blnMultiplePage = false;

        //add button to be disable in edit mode
        if (HttpContext.Current.Request.QueryString["CPY"] == null)
            if (HttpContext.Current.Request.QueryString["PK"] != null)
                blnMultiplePage = false;

        if (!objSec.getObjectRightsForUser(droPage["object_id"].ToString(), "create")) blnMultiplePage = false;


        if (blnMultiplePage)
        {
            if (dsinput == null)
            {
                btnAddObj = new Button();//Button btnAddObj = new Button();
                btnAddObj.ID = "btn_" + strPageId + "_Add_1";
                //btnAddObj.UseSubmitBehavior = true;
                btnAddObj.UseSubmitBehavior = false;
                btnAddObj.Text = "Add";
                btnAddObj.Click += new EventHandler(btnAddObj_Click);
                //btnAddObj.OnClientClick = "return AddRow('" + strPageId + "')";
                btnAddObj.OnClientClick = "AddRow('" + strPageId + "'); __doPostBack('" + btnAddObj.ID + "','')";
                //htcObj.Controls.Add(btnAddObj);
            }
        }



        if (htcObj.Controls.Count > 0)
        {
            //htcObj.Width = "250px";
            htcObj.Width = "33%";
            htcObj.Align = "Center";
            htrPageHeader.Cells.Add(htcObj);
            htcObj = new HtmlTableCell();
        }
        //htcObj.Width = "250px";
        htcObj.Width = "33%";

        if (blnMultiplePage)
        {
            htcObj.Align = "Center";
            if (dsinput == null)
            {
                htcObj.Controls.Add(btnAddObj);
            }
            htrPageHeader.Controls.Add(htcObj);
        }

        htcObj = new HtmlTableCell();

        // Added by srivatsan
        try
        {

            //if (HttpContext.Current.Request.QueryString["PK"] == null)
            //{

            //}

            if (HttpContext.Current.Request.Url.AbsoluteUri.ToLower().Contains("transdoc.aspx")) // Added on Apr 08 2009 for Transaction Document 
            {

            }
            else
            {

                if (HttpContext.Current.Request.QueryString["PK"] != null)
                {
                    Label lblprint = new Label();
                    lblprint.ID = "PFP" + HttpContext.Current.Request.QueryString["PK"];//added by jeya prabha on 12-May-2009
                    lblprint.Text = "<img src=\"Images/mb_button_print.GIF\" onclick=\"javascript:Popup=(window.open('Print.aspx?pgs_id=" + strPagesetRowId + "&PK=" + HttpContext.Current.Request.QueryString["PK"].ToString() + "&mn=" + HttpContext.Current.Request.QueryString["mn"].ToString() + "','Popup','toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=800,height=630,left=100,top=30')||window).focus(); return false;\" ></img>";
                    lblprint.ToolTip = "Printer friendly page";
                    lblprint.CssClass = "SearchPopup";

                    if (HttpContext.Current.Request.QueryString["VMODE"] != null)
                    {

                        if (HttpContext.Current.Request.QueryString["VMODE"] == "1")
                        {

                            lblprint.Visible = false;

                        }

                    }
                    htcObj.Controls.Add(lblprint);

                }
            }
        }
        catch
        {
        }



        //ImageButton imgHelp = new ImageButton(); // Commented by 'Imran Gani' on 24-Apr-2013.
        Image imgHelp = new Image();
        if (dsinput != null)// transaction document
        {
            imgHelp.ID = "imgHelp_transdoc";
        }
        else
        {
            imgHelp.ID = "imgHelp";
        }
        //imgHelp.ImageUrl = "images/ic_help.png";
        imgHelp.ImageUrl = "images/ic_help.png"; // Added by srivatsan on Feb 20 2009
        imgHelp.Visible = false;
        htcObj.Align = "right";
        htcObj.Controls.Add(imgHelp);
        htcObj.Controls.Add(new LiteralControl("&nbsp;"));
        htcObj.Width = "33%"; // 33
        htrPageHeader.Controls.Add(htcObj);


        htPageHeader.Attributes.Add("class", "Dynamic_PageHeaderRow");
        htPageHeader.Rows.Add(htrPageHeader);
        htcPageCell.Controls.Add(htPageHeader);
        htrObj.Cells.Add(htcPageCell);
        htaMain.Rows.Add(htrObj);
        return blnStatus;
    }

    void btnimgAddObj_Click(object sender, EventArgs e)
    {
        //   throw new Exception("The method or operation is not implemented.");
    }

    public DataTable getAllChildObjects(string strPagesetRowId)
    {
        DataTable dtChildObjects = new DataTable();
        try
        {
            string sPage_id = "";
            string sObject_Id = "";
            string sAF_ROW_ID = "";
            //string sSql = "select af_row_id from sy_pgs where pageset_id='" + strPagesetRowId + "'";
            //string sSql = "select pg.object_id from sy_pg pg inner join sy_pgs_mem pgs_mem on pg.page_id=pgs_mem.page_id inner join sy_pgs pgs on pgs.af_row_id=pgs_mem.pageset_id where pgs.pageset_id = '" + strPagesetRowId + "'";
            //sAF_ROW_ID = HDD.GetColumnValue(sSql);
            //sSql = "select page_id from sy_pgs_mem where pageset_id='" + sAF_ROW_ID + "'";
            //sPage_id = HDD.GetColumnValue(sSql);
            //sSql = "select object_id from sy_pg where page_id='" + sPage_id + "'";
            //sObject_Id = HDD.GetColumnValue(sSql);
            //sSql = "select * from sy_obj_mas_detail where master_obj = '" + sObject_Id + "'";
            //dtChildObjects = HDD.GetDataTable(sSql);
            //sAF_ROW_ID = CommonFunctions.GetColValueFromPageInfo(strPagesetRowId, "sy_pgs", "af_row_id", "pageset_id='" + strPagesetRowId + "'");
            sPage_id = CommonFunctions.GetColValueFromPageInfo(strPagesetRowId, "sy_pgs_mem", "page_id", "pageset_id='" + strPagesetRowId + "'");
            sObject_Id = CommonFunctions.GetColValueFromPageInfo(strPagesetRowId, "sy_pg", "object_id", "page_id='" + sPage_id + "'");
            dtChildObjects = HDD.GetDataTable("select * from sy_obj_mas_detail where master_obj = '" + sObject_Id + "'");
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getAllChildObjects : Error : " + ex.Message);
        }
        return dtChildObjects;
    }
    private bool manageADS()
    {
        bool breturn = false;
        try
        {

            HDDatabase hddAD = new HDDatabase(HttpContext.Current.Session["servercon"].ToString());
            DataTable dt = hddAD.GetDataTable("select * from ngcompany where company_id='" + HttpContext.Current.Session["company_id"].ToString() + "'");
            dt = hddAD.GetDataTable("select * from AD_Manager where company_id='" + dt.Rows[0]["af_row_id"].ToString() + "' and show_ads=1 order by sequence");
            if (dt != null)
                if (dt.Rows.Count > 0) breturn = true;

        }
        catch (Exception e)
        {
            LogWriter.WriteLog("manageADS : Error : " + e.Message);
        }
        return breturn;

    }
    public void getPagesetandLoad(DataTable dtChildObjects, HtmlForm frmobj)
    {
        GenerateGrid GG = null;
        try
        {
            string sPageset_id = "";
            foreach (DataRow dr in dtChildObjects.Rows)
            {
                sPageset_id = getPagesetId(dr["object_id"].ToString());
                GG = new GenerateGrid();
                if (sPageset_id != "")
                    GG.DisplayPage(sPageset_id, frmobj);
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getPagesetandLoad : Error : " + ex.Message);
        }
        finally
        {
            if (GG != null) GG = null;
        }
    }

    private string getPagesetId(string Object_Id)
    {
        string sPageset_Id = "";
        try
        {
            /* lines commented by 'Imran Gani' 29-Apr-2013, to reduce database traversal
            string sPage_id = "";
            string sAF_ROW_ID = "";
            string sSql = "";
            sSql = "select object_id from sy_obj where af_row_id='" + Object_Id + "'";
            Object_Id = HDD.GetColumnValue(sSql);
            sSql = "select page_id from sy_pg where object_id='" + Object_Id + "'";
            sPage_id = HDD.GetColumnValue(sSql);
            sSql = "select pageset_id from sy_pgs_mem where page_id='" + sPage_id + "'";
            sAF_ROW_ID = HDD.GetColumnValue(sSql);
            sSql = "select pageset_id from sy_pgs where af_row_id='" + sAF_ROW_ID + "'";
            sPageset_Id = HDD.GetColumnValue(sSql);*/
            // Below line added by 'Imran Gani' 29-Apr-2013, to reduce database traversal
            sPageset_Id = HDD.GetColumnValue("select pgs.af_row_id from [sy_pgs] pgs, [sy_obj] obj, [sy_pgs_mem] pgs_mem where obj.object_id = pgs_mem.object_id and pgs_mem.pageset_id = pgs.af_row_id and obj.af_row_id='" + Object_Id + "';");
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getPagesetId : Error : " + ex.Message);
        }
        return sPageset_Id;
    }

    private Literal GetPageIcons(string pageid) // Added by srivatsan for Icon Display in Pages
    {
        Literal iconlit = new Literal();
        PageIcons icons = new PageIcons();
        try
        {
            string icontext = icons.geticons(pageid, 2);
            icons = null;
            iconlit.Text = "&nbsp;<img src = " + icontext + "></img>&nbsp;";
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error GetPageIcons:" + ex.Message);
            iconlit.Text = "&nbsp;<img src = " + PageIcons.strdefaulticon.ToString() + "></img>&nbsp; ";
        }
        finally
        {
            icons = null;
        }
        return iconlit;


    }

    // Added by srivatsan on SEP 29 2009 for Notes changes
    // This function will get the values of the hidden fields in the Notes Page
    // This should be called only for notes page
    private string GetNotesHiddenFieldData(string attrib_id, DataSet dsPageInfo)
    {
        string result = "";
        try
        {
            switch (attrib_id)
            {
                case "p_notes_related_af_row_id":
                    result = HttpContext.Current.Request.QueryString["MK"].ToString();
                    break;
                case "p_notes_related_object_id":
                    if (dsPageInfo != null)
                    {
                        if (dsPageInfo.Tables["ObjectNotes"] != null)
                        {
                            if (dsPageInfo.Tables["ObjectNotes"].Rows.Count > 0)
                            {
                                result = dsPageInfo.Tables["ObjectNotes"].Rows[0]["af_row_id"].ToString();
                            }
                        }
                    }
                    break;
            }

        }
        catch
        {

        }
        finally
        {

        }

        return result;
    }

    private bool IsTransactionDocumentPage()
    {
        bool status = false;
        try
        {
            if (HttpContext.Current.Request.Url != null)
            {
                if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("transdoc.aspx"))
                {
                    status = true;
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : IsTransactionDocumentPage :" + ex.Message);
        }
        return status;
    }

    //Added by srivatsan 
    //This function will add Total Label to the HtmlTableCell
    private void AddTotalLabel(ref HtmlTable ht, int intpos)
    {
        try
        {
            if (ht != null)
            {
                int intprev = intpos - 1;
                if (intprev > 0)
                {
                    Control con = FindControl(ht.Controls, "td_trans_doc_sub_total_" + intprev);
                    if (con != null)
                    {
                        HtmlTableCell htctotal = (HtmlTableCell)con;
                        htctotal.Align = "Right";
                        Label lbl = new Label();
                        lbl.Text = "Total:";
                        lbl.CssClass = "controlLabelFont";
                        htctotal.Controls.Add(lbl);
                    }
                }
            }
        }
        catch (Exception ex)
        { LogWriter.WriteLog("Error : AddTotalLabel :" + ex.Message); }
    }

    #region Unused code
    ////private int AddTaxFields(HtmlTable ht, DataRow[] dr, DataRow[] totalfield, DataTable dtaPage, int rowcount, HtmlForm frm, HtmlTable htapagetable)
    ////{
    ////    HtmlTableRow htr = new HtmlTableRow();
    ////    HtmlTableCell htc = new HtmlTableCell();
    ////    int inttotalfieldtext = 0;
    ////    try
    ////    {
    ////        if (totalfield.Length > 0)
    ////        {
    ////            htr.Controls.Add(htc);

    ////            for (int i = 0; i < dr.Length; i++)
    ////            {
    ////                htc = new HtmlTableCell();
    ////                htc.ID = "td_trans_doc_sub_total_" + i;
    ////                for (int j = 0; j < totalfield.Length; j++)
    ////                {
    ////                    if (dr[i]["control_attrib_id"].ToString().ToLower() == totalfield[j]["attrib_id"].ToString().ToLower())
    ////                    {
    ////                        Label lbltotal = new Label();
    ////                        lbltotal.CssClass = "controlLabelFont";
    ////                        lbltotal.Text = "&nbsp;";
    ////                        string actualattrib_id = totalfield[j]["attrib_id"].ToString();
    ////                        string page_id = dtaPage.Rows[0]["page_id"].ToString();
    ////                        //GetTotalAmount(dtaPage.Rows[0]["page_id"].ToString(), rowcount, frm, htapagetable);
    ////                        //lbltotal.Text = totalfield[j]["attrib_id"].ToString();
    ////                        //lbltotal.CssClass = "controlLabelFont";
    ////                        lbltotal.ID = "total_" + page_id + "_" + actualattrib_id;
    ////                        htc.Controls.Add(lbltotal);
    ////                        htc.Align = "Right";

    ////                        inttotalfieldtext = i;

    ////                    }
    ////                    if (Convert.ToBoolean(dr[i]["control_visible"].ToString()))
    ////                    {
    ////                        htr.Controls.Add(htc);
    ////                    }

    ////                }
    ////                // htr.Controls.Add(htc);
    ////            }

    ////        }
    ////        ht.Controls.Add(htr);
    ////    }
    ////    catch (Exception ex)
    ////    {
    ////        LogWriter.WriteLog("Error Add Total Fields :" + ex.Message);
    ////    }
    ////    return inttotalfieldtext;
    ////}
    #endregion

    //Added by srivatsan
    //This function will Create TaxFields (percentage,taxamount)
    private void CreateTaxFields(DataSet dsTax, HtmlTable htPageTable, int intPos, HtmlForm frmobj)
    {
        try
        {
            string page_id = "";
            if (dsePageInfoMain != null)
            {
                if (dsePageInfoMain.Tables.Count > 0)
                    if (dsePageInfoMain.Tables["Page"] != null)
                        if (dsePageInfoMain.Tables["Page"].Rows.Count > 0)
                            page_id = dsePageInfoMain.Tables["Page"].Rows[0]["page_id"].ToString();
            }

            if (dsTax != null)
                if (dsTax.Tables.Count > 0)
                    if (dsTax.Tables["TaxRecords"] != null)
                        if (dsTax.Tables["TaxRecords"].Rows.Count > 0)
                            foreach (DataRow dr in dsTax.Tables["TaxRecords"].Rows)
                            {
                                if (dr["percentage_field"].ToString().Trim() != "" || dr["master_field"].ToString().Trim() != "")
                                    if (dsTax.Tables["PageCtrl"] != null)
                                    {
                                        int intcontrolPos = 0;
                                        if (intPos == 0)
                                        {
                                            GetAssociatedFieldGrandTotalPosition(dr["child_field"].ToString(), page_id, htPageTable, ref intcontrolPos);

                                            CreateTableRow(ref htPageTable, intcontrolPos, dr, dsTax.Tables["PageCtrl"], dsTax, frmobj);
                                        }
                                        else
                                        {
                                            CreateTableRow(ref htPageTable, intPos, dr, dsTax.Tables["PageCtrl"], dsTax, frmobj);
                                        }
                                    }
                            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : CreateTaxFields : " + ex.Message);
        }
    }

    //Added by srivatsan
    //This function will Create Grand Total Fields
    private void CreateGrandTotalFields(DataSet dsTax, HtmlTable htPageTable, int intPos, HtmlForm frmobj, Hashtable hshTotals)
    {
        try
        {
            string page_id = "";
            if (dsePageInfoMain != null)
            {
                if (dsePageInfoMain.Tables.Count > 0)
                    if (dsePageInfoMain.Tables["Page"] != null)
                        if (dsePageInfoMain.Tables["Page"].Rows.Count > 0)
                            page_id = dsePageInfoMain.Tables["Page"].Rows[0]["page_id"].ToString();
            }
            if (dsTax != null)
                if (dsTax.Tables.Count > 0)
                    if (dsTax.Tables["GrandTotal"] != null)
                        if (dsTax.Tables["GrandTotal"].Rows.Count > 0)
                            foreach (DataRow dr in dsTax.Tables["GrandTotal"].Rows)
                            {
                                if (dr["grand_total_attrib_id"].ToString().Trim() != "")
                                    if (dsTax.Tables["PageCtrl"] != null)
                                    {
                                        int igrandpos = 0;
                                        if (page_id.Trim() != "")
                                        {
                                            igrandpos = GetAssociatedFieldGrandTotalPosition(dr["associated_child_attrib_id"].ToString(), page_id, hshTotals);
                                        }
                                        if (igrandpos > 0)
                                        {
                                            CreateGrandTotalTableRow(ref htPageTable, igrandpos, dr, dsTax.Tables["PageCtrl"], dsTax, frmobj);
                                        }
                                        else
                                        {
                                            int intcontrolPos = 0;
                                            GetAssociatedFieldGrandTotalPosition(dr["associated_child_attrib_id"].ToString(), page_id, htPageTable, ref intcontrolPos);
                                            if (intcontrolPos > 0)
                                                CreateGrandTotalTableRow(ref htPageTable, intcontrolPos, dr, dsTax.Tables["PageCtrl"], dsTax, frmobj);
                                            else
                                                CreateGrandTotalTableRow(ref htPageTable, intPos, dr, dsTax.Tables["PageCtrl"], dsTax, frmobj);
                                        }
                                    }
                            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : CreateGrandTotalFields : " + ex.Message);
        }
    }
    private int GetAssociatedFieldGrandTotalPosition(string control_id, string page_id, Hashtable hshTotals)
    {
        int intpos = 0;
        try
        {
            if (control_id.Trim() != "")
            {
                string strctrl = page_id + "_" + control_id;

                if (hshTotals.Contains(strctrl))
                    if (hshTotals[strctrl].ToString() != "")
                        intpos = Convert.ToInt32(hshTotals[strctrl].ToString());
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetAssociatedFieldGrandTotalPosition : " + ex.Message);
        }
        return intpos;

    }

    private void GetAssociatedFieldGrandTotalPosition(string control_id, string page_id, HtmlTable htTotals, ref int iPos)
    {
        try
        {
            string strctrlid = page_id + "_" + control_id;
            if (htTotals != null)
                for (int i = 0; i < htTotals.Rows.Count; i++)
                {
                    for (int j = 0; j < htTotals.Rows[i].Cells.Count; j++)
                    {
                        if (htTotals.Rows[i].Cells[j].Controls.Count > 0)
                        {
                            foreach (Control con in htTotals.Rows[i].Cells[j].Controls)
                            {
                                if (con.ID != null)
                                    if (con.ID.Trim() != "")
                                        if (con.ID.Trim().ToLower().Contains(strctrlid))
                                        {
                                            iPos = j;
                                            return;
                                        }
                            }
                        }
                    }
                }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetAssociatedFieldGrandTotalPosition : " + ex.Message);
        }
    }


    // Added by srivatsan
    private void CreateTableRow(ref HtmlTable htTable, int intPos, DataRow dr, DataTable dtpageCtrl, DataSet dsTax, HtmlForm frmobj)
    {
        int totalcellcount = htTable.Rows[0].Cells.Count;
        try
        {
            HtmlTableRow htr = new HtmlTableRow();
            HtmlTableCell htc = new HtmlTableCell();
            int intstartPos = intPos - 2;
            int intInterPos = intPos - 1;
            for (int i = 0; i < totalcellcount; i++)
            {
                htc = new HtmlTableCell();
                if (i == intstartPos) // Create Label control
                {
                    DataRow[] drrpgctrl = dtpageCtrl.Select("control_id='" + dr["percentage_field"].ToString() + "'");
                    if (drrpgctrl.Length > 0)
                    {
                        Label lbl = new Label();
                        lbl.Text = drrpgctrl[0]["control_name"].ToString() + "&nbsp;";
                        lbl.CssClass = "controlLabelFont";
                        if (!Convert.ToBoolean(drrpgctrl[0]["control_visible"].ToString().Trim() != "" ? Convert.ToBoolean(drrpgctrl[0]["control_visible"].ToString().Trim()) : false))
                        {
                            lbl.Visible = false;
                        }
                        htc.Align = "Right";
                        //htc.NoWrap = true;
                        htc.Controls.Add(lbl);
                    }
                }
                if (i == intInterPos) //Create TextBox control for percentage field
                {
                    if (dr["percentage_field"].ToString().Trim() != "") // Check if percentage field can be shown
                    {
                        DataRow[] drrpgctrl = dtpageCtrl.Select("control_id='" + dr["percentage_field"].ToString() + "'");
                        if (drrpgctrl.Length > 0)
                            CreateTaxControl(drrpgctrl[0], drrpgctrl[0]["control_id"].ToString(), ref htc, dsTax, frmobj);
                    }
                    else // if percentage need not be shown
                    {
                        if (dr["master_field"].ToString().Trim() != "")
                        {
                            DataRow[] drrpgctrl = dtpageCtrl.Select("control_id='" + dr["master_field"].ToString() + "'");
                            if (drrpgctrl.Length > 0)
                            {
                                Label lbl = new Label();
                                lbl.Text = drrpgctrl[0]["control_name"].ToString() + "&nbsp;";
                                lbl.CssClass = "controlLabelFont";
                                if (!Convert.ToBoolean(drrpgctrl[0]["control_visible"].ToString().Trim() != "" ? Convert.ToBoolean(drrpgctrl[0]["control_visible"].ToString().Trim()) : false))
                                    lbl.Visible = false;
                                htc.Align = "Right";
                                //htc.NoWrap = true;
                                htc.Controls.Add(lbl);
                            }
                        }
                    }
                }
                if (i == intPos) // Create the tax amount field
                {
                    DataRow[] drrpgctrl = dtpageCtrl.Select("control_id='" + dr["master_field"].ToString() + "'");
                    if (drrpgctrl.Length > 0)
                        CreateTaxControl(drrpgctrl[0], drrpgctrl[0]["control_id"].ToString(), ref htc, dsTax, frmobj);
                }

                htc.NoWrap = true;
                htr.Controls.Add(htc);
            }
            htTable.Rows.Add(htr);

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : CreateTableRow : " + ex.Message);
        }

    }

    //Added by srivatsan
    private void CreateGrandTotalTableRow(ref HtmlTable htTable, int intPos, DataRow dr, DataTable dtpageCtrl, DataSet dsTax, HtmlForm frmobj)
    {
        int totalcellcount = htTable.Rows[0].Cells.Count;
        try
        {
            HtmlTableRow htr = new HtmlTableRow();
            HtmlTableCell htc = new HtmlTableCell();
            int intstartPos = intPos - 1;
            for (int i = 0; i < totalcellcount; i++)
            {
                htc = new HtmlTableCell();
                if (i == intstartPos)
                {
                    DataRow[] drrpgctrl = dtpageCtrl.Select("control_id='" + dr["grand_total_attrib_id"].ToString() + "'");
                    if (drrpgctrl.Length > 0)
                    {
                        Label lbl = new Label();
                        lbl.Text = drrpgctrl[0]["control_name"].ToString() + "&nbsp;";
                        lbl.CssClass = "controlLabelFont";
                        if (!Convert.ToBoolean(drrpgctrl[0]["control_visible"].ToString().Trim() != "" ? Convert.ToBoolean(drrpgctrl[0]["control_visible"].ToString().Trim()) : false))
                        {
                            lbl.Visible = false;
                        }
                        htc.Align = "Right";
                        htc.NoWrap = true;
                        htc.Controls.Add(lbl);
                    }
                }
                if (i == intPos)
                {
                    DataRow[] drrpgctrl = dtpageCtrl.Select("control_id='" + dr["grand_total_attrib_id"].ToString() + "'");
                    if (drrpgctrl.Length > 0)
                        CreateTaxControl(drrpgctrl[0], drrpgctrl[0]["control_id"].ToString(), ref htc, dsTax, frmobj);
                }
                htr.Controls.Add(htc);
            }
            htTable.Rows.Add(htr);

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : CreateGrandTotalTableRow : " + ex.Message);
        }
    }

    //Added by srivatsan 
    //This function will create the Control on the referred HtmlTableCell
    private void CreateTaxControl(DataRow drrpgctrl, string control_id, ref HtmlTableCell htc, DataSet dsTax, HtmlForm frmobj)
    {
        PageCommonFunctions PCF = new PageCommonFunctions();
        DataTable dtPageKeys = new DataTable();
        DataSet dsinput = new DataSet();
        ArrayList arrlist = new ArrayList();
        BindControl BC = new BindControl();
        try
        {
            if (drrpgctrl != null)
            {
                string page_id = "";
                DataRow[] drrtotal = null;
                string object_id = "";
                if (dsTax != null)
                {
                    if (dsTax.Tables["Page"] != null)
                    {
                        page_id = dsTax.Tables["Page"].Rows[0]["page_id"].ToString();
                        object_id = dsTax.Tables["Page"].Rows[0]["object_id"].ToString();
                    }
                    if (dsTax.Tables["PageKeys"] != null)
                    {
                        dtPageKeys = dsTax.Tables["PageKeys"];
                    }
                }
                string StrPageview = "1";
                int CurrentRow = 1;
                string strBindRowID = drrpgctrl["control_bind_id"].ToString();
                bool isReadOnly = drrpgctrl["read_only"].ToString() != "" ? Convert.ToBoolean(drrpgctrl["read_only"].ToString()) : false;
                bool isVisible = drrpgctrl["control_visible"].ToString() != "" ? Convert.ToBoolean(drrpgctrl["control_visible"].ToString()) : false;
                string strcontrol_id = page_id + "_" + drrpgctrl["control_id"].ToString();
                string actualcontrolid = drrpgctrl["control_id"].ToString();
                string strCtrlHTML = drrpgctrl["control_html"].ToString();
                string strCtrlDesc = "";
                string strCtrlWidth = drrpgctrl["control_width"].ToString();
                string strDefaultValue = drrpgctrl["default_value"].ToString();
                bool blnCaption = false;
                string strActualCtrlWidth = drrpgctrl["control_width"].ToString();
                string strobjid = object_id;
                string strAttrib_size = "";
                string isKey = "";
                string isprimary = "";
                bool ismultiplerecordpage = false;
                bool isEdit = true;
                if (!isViewMode())
                    isEdit = false;
                if (isReadOnly == true)
                    isEdit = false;
                string isRelational = "";
                string tooltip = "";
                string inputmask = drrpgctrl["input_mask_format"].ToString();
                if (dsTax.Tables["PageObjects"] != null)
                {
                    DataTable dtobjects = dsTax.Tables["PageObjects"];
                    DataRow[] drrobject = dtobjects.Select("attrib_id = '" + control_id + "'");
                    if (drrobject.Length > 0)
                    {
                        strAttrib_size = drrobject[0]["attrib_size"].ToString();
                        isKey = drrobject[0]["is_key"].ToString();
                        isprimary = drrobject[0]["is_primary"].ToString();
                        strCtrlDesc = drrobject[0]["attrib_description"].ToString();
                        tooltip = drrobject[0]["object_tooltip"].ToString();
                    }
                }
                PCF.ControlInit(htc, CurrentRow, StrPageview, strcontrol_id, strCtrlDesc, strBindRowID, strCtrlHTML, arrlist, false, BC, strDefaultValue, blnCaption, actualcontrolid, strCtrlWidth, strobjid, isKey, isprimary, ismultiplerecordpage, isEdit, strAttrib_size, drrpgctrl, dtPageKeys, isRelational, tooltip, inputmask, dsinput, drrtotal, frmobj, dsTax, page_id);
                if (arrlist.Count > 0)
                {
                    HtmlTableCell htccopy = (HtmlTableCell)arrlist[0];
                    htc = htccopy;
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : CreateTaxControl : " + ex.Message);
        }
        finally
        {
            PCF = null;
            dtPageKeys = null;
            dsinput = null;
            arrlist = null;
            BC = null;
        }
    }

    // This function will Associate Tax Controls with events
    private void SetEventsForTransDocTaxFields(DataSet dsTax, ref HtmlTable htPageTable, string childPageid)
    {
        try
        {
            if (dsTax != null)
                if (dsTax.Tables.Count > 0)
                {
                    if (htPageTable != null)
                        if (htPageTable.Rows.Count > 0)
                        {
                            SetEventForMasterTaxFields(ref htPageTable, dsTax);
                            SetEventForChildTaxFields(ref htPageTable, dsTax, childPageid);
                        }
                }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : SetEventsForTransDocTaxFields : " + ex.Message);
        }

    }
    // This will create Events for Tax Fields in Master table e.g. Grand Total, Tax Percentage, Tax amount
    private void SetEventForMasterTaxFields(ref HtmlTable htPageTable, DataSet dsTax)
    {
        try
        {
            string masterpage_id = "";
            if (dsTax.Tables["Page"] != null)
            {
                if (dsTax.Tables["Page"].Rows.Count > 0)
                    masterpage_id = dsTax.Tables["Page"].Rows[0]["page_id"].ToString();
                if (masterpage_id.Trim() != "")
                {
                    if (dsTax.Tables["GrandTotal"] != null)
                    {
                        DataTable dtgrand = dsTax.Tables["GrandTotal"];
                        if (dtgrand.Rows.Count > 0)
                            foreach (DataRow dr in dtgrand.Rows)  // Grand Total field
                            {
                                if (dr["grand_total_attrib_id"].ToString().Trim() != "")
                                {
                                    string grandtotalfield = masterpage_id + "_" + dr["grand_total_attrib_id"].ToString();
                                    Control con = FindControl(htPageTable.Controls, grandtotalfield);
                                    if (con != null)
                                        AssociateEventToControl(ref con, "transdoc_refreshTotalFields();");
                                }

                            }
                    }
                    if (dsTax.Tables["TaxRecords"] != null)
                    {
                        DataTable dttaxrecords = dsTax.Tables["TaxRecords"];
                        if (dttaxrecords.Rows.Count > 0)
                            foreach (DataRow dr in dttaxrecords.Rows)
                            {
                                if (dr["percentage_field"].ToString().Trim() != "") // e.g. Tax Percentage
                                {
                                    string percentagefield = masterpage_id + "_" + dr["percentage_field"].ToString();
                                    Control con = FindControl(htPageTable.Controls, percentagefield);
                                    if (con != null)
                                        AssociateEventToControl(ref con, "transdoc_refreshTotalFields();");
                                }
                                if (dr["master_field"].ToString() != null) // e.g tax_amount
                                {
                                    string masterfield = masterpage_id + "_" + dr["master_field"].ToString();
                                    Control con = FindControl(htPageTable.Controls, masterfield);
                                    if (con != null)
                                        AssociateEventToControl(ref con, "transdoc_refreshTotalFields();");
                                }
                            }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : SetEventForMasterTaxFields : " + ex.Message);
        }
    }
    // This will create events for Tax Fields in Child Table e.g. amount, taxable
    private void SetEventForChildTaxFields(ref HtmlTable htPageTable, DataSet dsTax, string childPageid)
    {
        try
        {
            if (dsTax.Tables["TaxRecords"] != null)
            {
                DataTable dt = dsTax.Tables["TaxRecords"];
                foreach (DataRow dr in dt.Rows)
                {
                    string childfield = dr["child_field"].ToString().Trim() != "" ? childPageid + "_" + dr["child_field"].ToString() : "";
                    string taxablefield = dr["taxable_field"].ToString().Trim() != "" ? childPageid + "_" + dr["taxable_field"].ToString() : "";

                    if (childfield.Trim() != "")
                    {
                        Control con = FindControl(htPageTable.Controls, childfield); //Child field e.g. amount
                        //if (con != null)
                        //AssociateEventToControl(ref con, "transdoc_refreshTotalFields();");
                    }

                    if (taxablefield.Trim() != "")
                    {
                        Control con = FindControl(htPageTable.Controls, taxablefield); // taxable field e.g. taxable checkbox
                        if (con != null)
                            AssociateEventToControl(ref con, "transdoc_refreshTotalFields();");
                    }

                    for (int i = 0; i < htPageTable.Rows.Count; i++)
                    {
                        if (childfield.Trim() != "") //Child field e.g. amount
                        {
                            Control con = FindControl(htPageTable.Controls, childfield + "_" + i);
                            if (con != null)
                                AssociateEventToControl(ref con, "transdoc_refreshTotalFields();");
                        }
                        if (taxablefield.Trim() != "") // taxable field e.g. taxable checkbox
                        {
                            Control con = FindControl(htPageTable.Controls, taxablefield + "_" + i);
                            if (con != null)
                                AssociateEventToControl(ref con, "transdoc_refreshTotalFields();");
                        }

                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error: SetEventForChildTaxFields :" + ex.Message);
        }
    }

    private void AssociateEventToControl(ref Control cn, string eventname)
    {
        try
        {
            if (cn is TextBox)
            {
                TextBox txt = (TextBox)cn;
                if (!CheckIfAttributeExists(txt.Attributes, eventname))
                    setAttribute(txt.Attributes, "onchange", "javascript:" + eventname + "");
                // txt.Attributes.Add("onchange", "javascript:" + eventname + "");
            }
            else if (cn is DropDownList)
            {
                DropDownList dd = (DropDownList)cn;
                if (!CheckIfAttributeExists(dd.Attributes, eventname))
                    setAttribute(dd.Attributes, "onchange", "javascript:" + eventname + "");
                //dd.Attributes.Add("onchange", "javascript:" + eventname + "");
            }
            else if (cn is CheckBox)
            {
                CheckBox chk = (CheckBox)cn;
                if (!CheckIfAttributeExists(chk.Attributes, eventname))
                    setAttribute(chk.Attributes, "onclick", "javascript:" + eventname + "");
                //chk.InputAttributes.Add("onclick", "javascript:" + eventname + "");
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : AssociateEventToControl : " + ex.Message);
        }
    }

    private bool CheckIfAttributeExists(AttributeCollection attr, string strkey)
    {
        bool status = false;
        try
        {
            if (attr != null)
                if (attr.Count > 0)
                    foreach (string keys in attr.Keys)
                    {
                        if (attr[keys].ToLower().Contains(strkey.ToLower()))
                            status = true;
                    }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : CheckIfAttributeExists : " + ex.Message);
        }
        return status;
    }

    public void setAttribute(AttributeCollection ac, string attrName, string attrValue)//by sanal on Oct 30, 2009
    {
        try
        {
            string temp = "";
            foreach (string keys in ac.Keys)
            {
                if (keys == attrName)
                {
                    temp = ac[keys];
                    ac.Remove(attrName);
                    break;
                }
            }
            if (temp.IndexOf("javascript:") > -1)
            {
                temp += attrValue;
                temp = "javascript:" + temp.Replace("javascript:", "");
            }
            else
                temp += attrValue;
            ac.Add(attrName, temp);
            //code to enhance attribute handling
        }
        catch (Exception e)
        {

        }
    }

    private void SetHiddenValues(ref HiddenField hf, HtmlForm frmObj)
    {
        try
        {
            if (hf != null)
            {
                string id = hf.ID;
                //Control con = frmObj.FindControl(id);
                //if (con != null)
                //{
                if (frmObj.Page.Request.Form["ctl00$" + id] != null)
                {
                    string strpostbackvalue = frmObj.Page.Request.Form["ctl00$" + id].ToString();
                    hf.Value = strpostbackvalue;
                }
                //}

            }

        }
        catch
        {
        }


    }




}

